有人可以告诉我,以下 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;
^
Doing
unique_ptr<int> px(new int);
工作得很好。
这两段代码的初始化都很好,unique_ptr
has 构造函数 http://en.cppreference.com/w/cpp/memory/unique_ptr/unique_ptr对彼此而言nullptr
和裸指针。
第一个片段中失败的是分配,那是因为unique_ptr
没有operator= http://en.cppreference.com/w/cpp/memory/unique_ptr/operator%3D接受裸指针作为其右侧的重载。它确实接受另一个unique_ptr
不过,你可以这样做:
py = unique_ptr<int>{new int};
py = std::make_unique<int>(); // Since c++14
或者你可以看看reset http://en.cppreference.com/w/cpp/memory/unique_ptr/reset它也接受裸指针并且具有或多或少相同的含义:
py.reset(new int);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)