是否可以将 std::unique_ptr 移动到自身?

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

我有一种情况想要 unique_ptr 可以是 class 或其装饰器,如下所示:

std::unique_ptr<Base> b = std::make_unique<Derived>();

if (needsDecorator)
{
   b = std::make_unique<Decorator>(std::move(b));
}

哪里

class Derived: public Concrete {...}
class DecoratorC : public Base {...}

b移动到自身无效吗?

谢谢!

您正在从一个旧指针创建一个新的唯一指针,而不是将一个指针移入其自身。

如果这段代码运行:

pClass = std::make_unique<ClassDecorator>(std::move(pClass));

它将获取 pClass,在从中构造 ClassDecorator 时移动它。但是,您的 ClassDecorator class 需要一个采用 unique_ptr 的构造函数才能正常工作。

下面是一个示例,可以说明装饰后的 class 需要什么:

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