When a class has a unique_ptr of a Base class what is a good way to implement the copy constructor.
Let me try to explain it with an example:
struct Base
{
virtual void doSth() = 0; // to make the class abstract.
};
struct Derived : public Base
{
virtual void doSth() override {}
};
struct Foo
{
std::unique_ptr<Base> bar;
Foo(const Foo& other) : bar(new Base(*other.bar)) // cant do it, its abstract.
{
bar = std::move(other.bar); // cant do it, reference object is modified.
}
};
Here as the class is abstract i cannot use its copy constructor. and also cannot use move on a constant reference ( we shouldnt do it actually, do not modify the object).
What I end up with is like so:
struct Base
{
virtual void doSth() = 0; // to make the class abstract.
};
struct Derived : public Base
{
virtual void doSth() override {}
Derived(const Base* b)
{
}
};
struct Foo
{
std::unique_ptr<Base> bar;
Foo(const Foo& other) : bar(new Derived(other.bar.get()))
{
}
};
However, it does not feel quite right, does it?