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)
为什么不编译?如何将 native 指针附加到现有的 unique_ptr 实例?
最佳答案
首先,如果你需要一个独特的数组,就制作它
std::unique_ptr<int[]> ptr;
// ^^^^^
这允许智能指针正确使用 delete[]
来释放指针,并定义 operator[]
来模拟普通数组。
然后,operator=
只为唯一指针的右值引用定义,而不是原始指针,并且原始指针不能隐式转换为智能指针,以避免破坏唯一性的意外赋值。因此不能直接将原始指针分配给它。正确的做法是把它放到构造函数中:
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);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^
关于c++ - unique_ptr 运算符=,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9393874/