Ale*_*x F 10 c++ smart-pointers visual-studio-2010 c++11
std::unique_ptr<int> ptr;
ptr = new int[3]; // error
Run Code Online (Sandbox Code Playgroud)
error C2679: binary '=' : no operator found which takes a right-hand operand of type 'int *' (or there is no acceptable conversion)
为什么这不编译?如何将本机指针附加到现有的unique_ptr实例?
ken*_*ytm 29
首先,如果你需要一个独特的阵列,那就去做吧
std::unique_ptr<int[]> ptr;
// ^^^^^
Run Code Online (Sandbox Code Playgroud)
这允许智能指针正确地用于delete[]解除分配指针,并定义operator[]模仿正常数组.
然后,operator=仅为唯一指针的rvalue引用而不是原始指针定义,并且原始指针不能隐式转换为智能指针,以避免意外分配打破唯一性.因此,无法直接为其指定原始指针.正确的方法是将它放到构造函数中:
std::unique_ptr<int[]> ptr (new int[3]);
// ^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
或使用.reset功能:
ptr.reset(new int[3]);
// ^^^^^^^ ^
Run Code Online (Sandbox Code Playgroud)
或者将原始指针显式转换为唯一指针:
ptr = std::unique_ptr<int[]>(new int[3]);
// ^^^^^^^^^^^^^^^^^^^^^^^ ^
Run Code Online (Sandbox Code Playgroud)
如果你可以使用C++ 14,那么更喜欢使用的make_unique功能new:
ptr = std::make_unique<int[]>(3);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)