如何在类构造函数中创建新值并分配给私有unique_ptr?

kmi*_*las 3 c++ smart-pointers unique-ptr c++11

如何在类的构造函数中创建new并为私有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;
}
Run Code Online (Sandbox Code Playgroud)

编译结果:

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

Vla*_*cow 9

A::A(int a) : int_ptr_( new int(a) )
{
}
Run Code Online (Sandbox Code Playgroud)

或者你可以写

A::A(int a) 
{
    int_ptr_.reset( new int(a) );
}
Run Code Online (Sandbox Code Playgroud)

要么

A::A(int a) 
{
    int_ptr_ = std::make_unique<int>( a );;
}
Run Code Online (Sandbox Code Playgroud)

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