unique_ptr运算子= [英] unique_ptr operator=

查看:85
本文介绍了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实例?

Why this is not compiled? How can I attach native pointer to existing unique_ptr instance?

推荐答案

首先,如果需要唯一的数组,则将其制成

Firstly, if you need an unique array, make it

std::unique_ptr<int[]> ptr;
//              ^^^^^

这使智能指针可以正确地使用 delete [] 释放指针,并定义 operator [] 来模仿普通数组.

This allows the smart pointer to correctly use delete[] to deallocate the pointer, and defines the operator[] to mimic a normal array.

然后, operator = 仅为唯一指针的右值引用而不是原始指针定义,并且不能将原始指针隐式转换为智能指针,以避免意外分配破坏唯一性.因此,原始指针不能直接分配给它.正确的方法放在构造函数上:

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:

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

或使用 .reset 函数:

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

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

or explicitly convert the raw pointer to a unique pointer:

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

如果可以使用C ++ 14,请使用 make_unique 函数完全使用 new :

If you can use C++14, prefer the make_unique function over using new at all:

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

这篇关于unique_ptr运算子=的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆