初始化unique_ptr有什么问题? [英] What's wrong with this initialization of unique_ptr?
问题描述
有人可以告诉我,下面的unique_ptr初始化有什么问题吗?
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说:
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;
^
做
unique_ptr<int> px(new int);
工作正常.
推荐答案
The initialization is fine in both pieces of code, unique_ptr
has constructors for both nullptr
and naked pointers.
第一个代码段中失败的是分配,这是因为unique_ptr
没有
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
或者您可以查看 reset
,它也可以接受裸露的指针并具有更多内容或更少的意思:
Or you could look at reset
that also accepts a naked pointer and has more or less the same meaning:
py.reset(new int);
这篇关于初始化unique_ptr有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!