错误 C2248:"std::unique_ptr<_Ty>::unique_ptr":无法访问类"std::unique_ptr<_Ty>"中声明的私有成员

error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>'

本文关键字:ptr unique gt lt Ty std 声明 成员 错误 C2248 访问      更新时间:2023-10-16

目前我正在尝试使用std::unique_ptr,但是在Visual Studio 2012中遇到编译器错误。

class A
{
private:
 unique_ptr<A> other;
public:
 unique_ptr<A> getOther()
 {
   return other;
 }
};

错误是:

error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>'
with
[
    _Ty=A
]
c:program files (x86)microsoft visual studio 11.0vcincludememory(1447) : see declaration of 'std::unique_ptr<_Ty>::unique_ptr'
with
[
    _Ty=A
]
我相信

std::unique_ptr可以是一个返回类型,如果返回的值是本地范围的(即,一旦它退出函数就会被销毁)。在您的情况下不是,因为您返回的是unique_ptr<A> other,它在类有效时具有生命周期。