The Human class turned out to be non-copied, since it contains a field of type unique_ptr, for which the copy constructor and the copying assignment operator have been removed. This prevents the compiler from automatically generating a copy constructor and assignment operator for the Human class. How can I implement a copy constructor and a copy assignment operator in the Human class? A copy of the human must own a copy of the cat, if the original human owned it.
struct Cat {
Cat(const string& name, int age)
: name_(name)
, age_(age) //
{
}
const string& GetName() const noexcept {
return name_;
}
int GetAge() const noexcept {
return age_;
}
~Cat() {
}
void Speak() const {
cout << "Meow!"s << endl;
}
private:
string name_;
int age_;
};
unique_ptr<Cat> CreateCat(const string& name) {
return make_unique<Cat>(name, 2);
}
class Human {
public:
explicit Human(const string& name)
: name_(name) {
}
const string& GetName() const noexcept {
return name_;
}
void SetCat(unique_ptr<Cat>&& cat) noexcept {
cat_ = std::move(cat);
}
unique_ptr<Cat> ReleaseCat() noexcept {
return std::move(cat_);
}
private:
string name_;
unique_ptr<Cat> cat_;
};
CodePudding user response:
Your copy constructor might look like
Human::Human(const Human& rhs) :
name_(rhs.name_),
cat_(rhs.cat_ ? std::make_unique<Cat>(*rhs.cat_) : std::nullptr)
{}
but getting rid of std::unique_ptr
and having Cat
by value (or std::optional<Cat>
) would be simpler:
Human::Human(const Human&) = default;
If Cat
is polymorphic, a clone
method would be required:
Human::Human(const Human& rhs) :
name_(rhs.name_),
animal_(rhs.animal_ ? rhs.animal_->clone() : std::nullptr)
{}