Reputation: 43
I have a situation where I would like a unique_ptr
that could be a class, or its decorator as follows:
std::unique_ptr<Base> b = std::make_unique<Derived>();
if (needsDecorator)
{
b = std::make_unique<Decorator>(std::move(b));
}
where
class Derived: public Concrete {...}
class DecoratorC : public Base {...}
Is moving b
to itself invalid?
Thank you!
Upvotes: 0
Views: 222
Reputation: 6131
You are creating a new unique pointer from an old one, not moving one into itself.
If this code ran:
pClass = std::make_unique<ClassDecorator>(std::move(pClass));
It would take the pClass, move it while constructing a ClassDecorator from it. However, your ClassDecorator class would need to have a constructor that takes a unique_ptr for this to work.
Here's an example that may show what the decorated class needs:
#include <memory>
class Base {
virtual ~Base() = default;
};
class Derived : public Base
{
};
class Decorated : public Base {
std::unique_ptr<Base> ptr;
public:
// THIS CONSTRUCTOR (or something like it) is what's missing
Decorated(std::unique_ptr<Base> other) : ptr(std::move(other)) { }
};
int main()
{
std::unique_ptr<Base> something = std::make_unique<Derived>();
something = std::make_unique<Decorated>(std::move(something));
}
Upvotes: 1