What's wrong with this initialization of unique_ptr?

丶灬走出姿态 提交于 2019-12-21 13:09:11

问题


Can somebody tell me, what is wrong with the following initialization of unique_ptr?

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

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

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

Doing

unique_ptr<int> px(new int);

works just fine.


回答1:


The initialization is fine in both pieces of code, unique_ptr has constructors for both nullptr and naked pointers.

What is failing in the first snippet is the assignment, that is because unique_ptr does not have an operator= overload that accepts a naked pointer as its right hand side. It does accept another unique_ptr though, so you could do this:

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

Or you could look at reset that also accepts a naked pointer and has more or less the same meaning:

py.reset(new int);



回答2:


Regarding

what is wrong with the following initialization of unique_ptr?

It's not the initialization that's problematic, it's the following assignment.

That's where the caret (up arrow) in the error message points: at the assignment. Strong hint: use the reset member function, or create a unique_ptr instance.


Regarding

doing

unique_ptr<int> px(new int);

just works fine.

It's the assignment, of a raw pointer to a unique_ptr, that's problematic, not the initialization.



来源:https://stackoverflow.com/questions/28853309/whats-wrong-with-this-initialization-of-unique-ptr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!