C++ 什么';unique_ptr的初始化有什么问题?

C++ 什么';unique_ptr的初始化有什么问题?,c++,c++11,initialization,unique-ptr,C++,C++11,Initialization,Unique Ptr,有人能告诉我,下面的unique_ptr初始化有什么问题吗 int main() { unique_ptr<int> py(nullptr); py = new int; .... } intmain() { 唯一_ptr py(nullptr); py=新的int; .... } g++-O2 xxx.cc-lm-o xxx-std=c++11表示: error: no match for ‘operator=’ (operand types are ‘std

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

int main()
{
  unique_ptr<int> py(nullptr);
  py = new int;
  ....
}
intmain()
{
唯一_ptr py(nullptr);
py=新的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;
      ^
错误:“operator=”不匹配(操作数类型为“std::unique_ptr”和“int*”)
py=新的int;
^

unique_ptr px(新整数);
很好用。

关于

以下unique\u ptr初始化有什么问题

int main()
{
  unique_ptr<int> py(nullptr);
  py = new int;
  ....
}
问题不在于初始化,而在于下面的赋值

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


关于

unique_ptr<int> px(new int);
unique_ptr px(新整数);
很好用


有问题的是分配一个指向
unique\u ptr
的原始指针,而不是初始化。

初始化在两段代码中都很好,
unique\u ptr
nullptr
和裸指针都有作用

第一个代码段中失败的是赋值,这是因为
unique\u ptr
没有接受裸指针作为其右侧的重载。但它确实接受另一个
唯一的\u ptr
,因此您可以这样做:

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

尝试
py.reset(新int)
py=std::make_unique()
@KonradRudolph:我觉得你的评论很冒犯。但是你改变了答案。非常感谢所有回答的人——这非常有帮助!
py.reset(new int);