【问题标题】:How to create a new value and assign to a private unique_ptr in a class constructor?如何在类构造函数中创建新值并分配给私有 unique_ptr?
【发布时间】:2017-01-10 00:48:30
【问题描述】:

如何在类的构造函数中创建新的并将值分配给私有的 unique_ptr? Tyvm :^) 基思

我尽力了:

#include <iostream>
#include <memory>

class A {
public:
    A() {};
    A(int);
    void print();
private:
    std::unique_ptr<int> int_ptr_;
};
A::A(int a) {
    int_ptr_ = new int(a);
}
void A::print() {
    std::cout << *int_ptr_ << std::endl;
}
int main() {
    A a(10);
    a.print();
    std::cout << std::endl;
}

编译结果:

smartPointer2.1.cpp:13:11: error: no match for ‘operator=’ (operand types are ‘std::unique_ptr<int>’ and ‘int*’)
  int_ptr_ = new int(a);

【问题讨论】:

    标签: c++ c++11 smart-pointers unique-ptr


    【解决方案1】:

    A::A(int a) : int_ptr_( new int(a) )
    {
    }
    

    或者你可以写

    A::A(int a) 
    {
        int_ptr_.reset( new int(a) );
    }
    

    A::A(int a) 
    {
        int_ptr_ = std::make_unique<int>( a );;
    }
    

    第一种方法更好,因为在其他两种中,除了默认构造函数之外,还调用了一个附加方法或移动赋值运算符。

    【讨论】:

    • 第一个初始化成员变量,这意味着它在用户提供的构造函数开始之前就地准备就绪。我更喜欢这种方法,因为它意味着避免未初始化变量带来的一整类缺陷。另一方面,std::make_unique 在内存布局方面具有优势,也不应该被忽视:stackoverflow.com/questions/22571202/…
    • 忽略上面关于内存布局的评论,因为它只适用于shared_ptr。 Sutter 有一篇很好的 GotW 帖子,介绍了共享指针和唯一指针的一般用法:herbsutter.com/2013/05/29/gotw-89-solution-smart-pointers
    • 可以在构造函数初始化列表中使用std::make_unique(),例如:A::A(int a) : int_ptr_( std::make_unique&lt;int&gt;( a ) ) {}
    猜你喜欢
    • 2017-10-29
    • 2013-11-05
    • 1970-01-01
    • 2013-03-27
    • 2013-08-16
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    • 2015-02-11
    相关资源
    最近更新 更多