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 实例?
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)
Why this is not compiled? How can I attach native pointer to existing unique_ptr instance?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,如果您需要一个唯一的数组,请创建它。
这允许智能指针正确使用
delete[]
来释放指针,并定义operator[]
来模仿正常数组。然后,operator=仅定义为唯一指针的右值引用,而不是原始指针,并且原始指针不能隐式转换为智能指针,以避免意外赋值破坏唯一性。因此,原始指针不能直接分配给它。正确的方法是将其放入构造函数:
或使用
.reset
函数:或显式将原始指针转换为唯一指针:
如果您可以使用 C++14,则更喜欢
make_unique
函数 优于使用new
完全:Firstly, if you need an unique array, make it
This allows the smart pointer to correctly use
delete[]
to deallocate the pointer, and defines theoperator[]
to mimic a normal array.Then, the
operator=
is only defined for rvalue references of unique pointers and not raw pointers, and a raw pointer cannot be implicitly converted to a smart pointer, to avoid accidental assignment that breaks uniqueness. Therefore a raw pointer cannot be directly assigned to it. The correct approach is put it to the constructor:or use the
.reset
function:or explicitly convert the raw pointer to a unique pointer:
If you can use C++14, prefer the
make_unique
function over usingnew
at all:添加到答案中
KennyTM
(C++11 起)
我个人更喜欢这个,因为它使更新 tr 的类型变得更容易。 (只有一个地方需要更新)
Adding to the answer from
KennyTM
(since C++11)
Personally I prefer this as it makes updating the type of tr easier. (Only single place to update)