c++ - unique_ptr 运算符=

标签 c++ visual-studio-2010 c++11 smart-pointers

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/

相关文章:

c++ - 有没有办法在条件语句中声明对象?

c++ - 线程终止

c++ - 在 Visual Studio 2010 上使用 FFMPEG 解码

c++ - 在 C++ 中转换类型时出错

c# - 我在尝试获取当前位置时得到 NAN - 经度和纬度

c++ - "#define TYPE(x) typename decltype(x)"是个坏主意吗?

c++ - 如何使用 aligned_storage 和多态性避免未定义的行为

android - 如何在 Android JNI 中设置文件路径?

c++ - 如何设计我的类(class)?

C++ MFC double 到 CString