unique_ptr 运算符=

2024-01-02

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;
//              ^^^^^

这使得智能指针能够正确使用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功能 http://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique过度使用new at all:

ptr = std::make_unique<int[]>(3);
//    ^^^^^^^^^^^^^^^^^^^^^^^^^^
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

unique_ptr 运算符= 的相关文章

随机推荐