简体   繁体   中英

Is it possible to move a std::unique_ptr to itself?

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!

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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM