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



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

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

最新更新