[英]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:我有一种情况,我想要一个可以是 class 或其装饰器的
unique_ptr
,如下所示:
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?将
b
移动到自身无效吗?
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.它将采用 pClass,在从中构造 ClassDecorator 时移动它。 However, your ClassDecorator class would need to have a constructor that takes a unique_ptr for this to work.
但是,您的 ClassDecorator class 需要有一个带有 unique_ptr 的构造函数才能工作。
Here's an example that may show what the decorated class needs:这是一个示例,可以显示装饰的 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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.