如何构造具有unique_ptr成员的对象

How do I construct an object that has a unique_ptr member?

本文关键字:ptr 成员 对象 unique 何构造      更新时间:2023-10-16

我有一个基类:

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