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

How to create a new value and assign to a private unique_ptr in a class constructor?

如何在 class 的构造函数中创建新的并为私有 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);

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

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