如何构造具有unique_ptr成员的对象
How do I construct an object that has a unique_ptr member?
我有一个基类:
class Base {
public:
Base(??? new_p) : p(new_p) {}
std::unique_ptr<MyType> p;
}
和一个派生类:
class Derived : public Base {
Derived(??? new_p) : Base(new_p) {}
}
如果要构造Derived
,我应该用什么类型替换问号?其他改变也很好。我想确保可以在不复制p
指向MyType
的情况下构建Derived
。
取决于你想要支持什么 - 下面的一个或两个构造函数都有意义,来自MyType*
或std::unique_ptr<MyType>&&
,这需要调用方提供可移动unique_ptr
。 简单地使用 std::unique_ptr<MyType>
也可以,因为std::unique_ptr
有一个来自其他可移动实例的构造函数......只是品味问题,是否要在您自己的代码中强调调用方传入unique_ptr
的必然瞬态性质。
class Base
{
public:
Base(MyType* new_p) : p(new_p) { }
Base(std::unique_ptr<MyType>&& new_p) : p(std::move(new_p)) { }
std::unique_ptr<MyType> p;
};
class Derived : public Base
{
public:
Derived(MyType* new_p) : Base(new_p) { }
Derived(std::unique_ptr<MyType>&& new_p) : Base(std::move(new_p)) { }
};
在这里看到它运行
我会用std::unique_ptr<MyType>
替换???
,然后在mem初始化器中std::move
它。
class Base {
public:
Base(std::unique_ptr<MyType> new_p) : p(std::move(new_p)) {}
std::unique_ptr<MyType> p;
};
class Derived : public Base {
Derived(std::unique_ptr<MyType> new_p) : Base(std::move(new_p)) {}
};
您也可以使用 std::unique_ptr<MyType>&&
而不是 std::unique_ptr<MyType>
并避免std::move
,但由于本答案中列出的原因,我更喜欢按值方法。
我建议不要采取MyType *
论点。该解决方案的问题在于,它不会向用户传达您获取传递给构造函数的指针所有权的意图。
这对
我有用。编辑以注意我使用字符串作为类型只是为了使其更易于阅读,您必须将其替换为您的类型。
#include <memory>
#include <string>
#include <iostream>
#include <utility>
class Base {
public:
Base(std::unique_ptr<std::string> new_p)
: p(std::move(new_p)) {}
std::unique_ptr<std::string> p;
};
class Derived : public Base {
public:
Derived(std::unique_ptr<std::string> new_p)
: Base(std::move(new_p)) {}
};
int main(){
std::unique_ptr<std::string> text(new std::string("Hello world"));
Derived a(std::move(text));
std::cout << *(a.p);
}
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 助记符和指向成员语法的指针
- 用于访问容器<T>数据成员的正确 API
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 嵌套在类中时无法设置成员数据
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 将函数类成员映射到类本身内部
- 初始pointCloudt :: PTR类成员
- 通过成员函数将唯一 ptr 的向量附加到另一个向量
- LNK 2001 未解析的外部在 NPPluginFuncs 结构 ptr 作为静态类成员
- 我应该通过引用、值或ptr来存储一个完全封装的成员吗
- 从虚拟成员函数ptr中进行类型推导(bug?)
- 一个唯一的ptr类如何将它的实例指针传递给它的成员对象
- ptr到成员模板参数的友元语法