【发布时间】:2016-08-16 21:58:02
【问题描述】:
编辑: 我知道 unique_ptr 是不可复制的,只能移动。我不明白初始化列表会发生什么。
为什么成员初始化列表中的 unique_ptr 可以像代码片段一样工作?
#include <memory>
class MyObject
{
public:
MyObject() : ptr(new int) // this works.
MyObject() : ptr(std::unique_ptr<int>(new int))
// i found this in many examples. but why this also work?
// i think this is using copy constructor as the bottom.
{
}
MyObject(MyObject&& other) : ptr(std::move(other.ptr))
{
}
MyObject& operator=(MyObject&& other)
{
ptr = std::move(other.ptr);
return *this;
}
private:
std::unique_ptr<int> ptr;
};
int main() {
MyObject o;
std::unique_ptr<int> ptr (new int);
// compile error, of course, since copy constructor is not allowed.
// but what is happening with member initialization list in above?
std::unique_ptr<int> ptr2(ptr);
}
【问题讨论】:
标签: c++ c++11 constructor initialization unique-ptr