的unique_ptr运营商=
问题描述:
std::unique_ptr<int> ptr;
ptr = new int[3]; // error
error C2679: binary '=' : no operator found which takes a right-hand operand of type 'int *' (or there is no acceptable conversion)
为什么这不是编译?我如何将本地指针附加到现有的unique_ptr实例?的unique_ptr运营商=
答
首先,如果你需要一个独特的阵列,使其
std::unique_ptr<int[]> ptr;
// ^^^^^
这使得智能指针正确使用delete[]
解除分配指针,并定义operator[]
模仿正常的阵列。
然后,operator=
仅针对独特指针rvalue引用,而不是原始指针定义,并且原始指针不能被隐式转换为智能指针,以避免打破唯一意外分配。因此原始指针不能直接分配给它。正确的做法是把它的构造器:
std::unique_ptr<int[]> ptr (new int[3]);
// ^^^^^^^^^^^^
或使用.reset
功能:
ptr.reset(new int[3]);
// ^^^^^^^ ^
或明确的原始指针转换为唯一指针:
ptr = std::unique_ptr<int[]>(new int[3]);
// ^^^^^^^^^^^^^^^^^^^^^^^ ^
如果您可以使用C++ 14,更喜欢make_unique
function完全可以使用new
:
ptr = std::make_unique<int[]>(3);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^
原因是'operator ='不接受'int *'*和* * int *构造函数被标记为'explicit'(对于'std :: unique_ptr '和'std :: unique_ptr ')。 'operator ='是一个移动赋值操作符,而不是一个拷贝赋值操作符与它无关。 –
2012-02-22 14:31:29
@LucDanton:对。已更新以包含该内容。 – kennytm 2012-02-22 20:05:05