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

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

我有一个基地class:

class Base {
public:
    Base(??? new_p) : p(new_p) {} 
    std::unique_ptr<MyType> p;
}

和派生的class:

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

看到了运行here

我会将 ??? 替换为 std::unique_ptr<MyType>,然后 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,但出于 this answer 中列出的原因,我更喜欢按值方法。

我建议不要采取 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);
}