0

我想知道返回智能指针有什么问题。编译器抛出构造函数本身已被删除。所以我尝试返回引用并且它有效,为什么这可能?

#include <iostream>
#include <memory>
using namespace std;

using unique_int = std::unique_ptr<int>;
unique_int p_Int = std::make_unique<int>();

unique_int GetPtr()
{
    return p_Int;
}

unique_int& GetPtrAddr()
{
    return p_Int;
}

错误信息是

function "std::unique_ptr<_Ty, _Dx>::unique_ptr(const std::unique_ptr<_Ty, _Dx>&)[with _Ty=int, Dx=std::default_delete<int>]"(declared at line 3269 of "memory library path") cannot be referenced -- it is a deleted function
4

1 回答 1

3

std::unique_ptr让我们检查一下当您按值 返回 a 时会发生什么。unique_int函数创建一个std::unique_ptr类型的临时对象,为该对象复制初始化临时std::unique_ptrfrom p_int,您将返回该对象。但它的全部意义std::unique_ptr在于它无法复制,只能移动

于 2021-09-24T10:35:33.100 回答