加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – unique_ptr operator =

发布时间:2020-12-16 06:43:32 所属栏目:百科 来源:网络整理
导读:std::unique_ptrint 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;
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 =仅针对唯一指针而不是原始指针的rvalue引用定义,并且原始指针不能被隐式转换为智能指针,以避免意外分配,从而破坏唯一性.因此,原始指针不能直接分配给它.将正确的方法放在构造函数中:

std::unique_ptr<int[]> ptr (new int[3]);
//                         ^^^^^^^^^^^^

或使用.reset函数:

ptr.reset(new int[3]);
// ^^^^^^^          ^

或将原始指针显式转换为唯一指针:

ptr = std::unique_ptr<int[]>(new int[3]);
//    ^^^^^^^^^^^^^^^^^^^^^^^          ^

如果可以使用C14,那么更喜欢make_unique function使用新的:

ptr = std::make_unique<int[]>(3);
//    ^^^^^^^^^^^^^^^^^^^^^^^^^^

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读