这个 unique_ptr 的初始化有什么问题?

What's wrong with this initialization of unique_ptr?

有人能告诉我,unique_ptr 的以下初始化有什么问题吗?

int main()
{
  unique_ptr<int> py(nullptr);
  py = new int;
  ....
}

g++ -O2 xxx.cc -lm -o xxx -std=c++11 说:

error: no match for ‘operator=’ (operand types are    ‘std::unique_ptr<int>’ and ‘int*’)
   py = new int;
      ^

正在做

unique_ptr<int> px(new int);

工作正常。

关于

what is wrong with the following initialization of unique_ptr?

不是初始化有问题,而是下面的赋值。

这就是错误消息中插入符号(向上箭头)指向的位置:赋值处。强烈提示:使用reset成员函数,或者创建一个unique_ptr实例。


关于

doing

unique_ptr<int> px(new int);

just works fine.

有问题的是指向 unique_ptr 的原始指针的赋值,而不是初始化。

两段代码的初始化都很好,unique_ptr nullptr 和裸指针都有 constructors

第一个代码片段中失败的是赋值,这是因为 unique_ptr 没有接受裸指针作为其右侧的 operator= 重载。不过它确实接受另一个 unique_ptr,所以你可以这样做:

py = unique_ptr<int>{new int};
py = std::make_unique<int>(); // Since c++14

或者您可以查看 reset,它也接受裸指针并且具有大致相同的含义:

py.reset(new int);