C++ 为什么C2662错误没有';t适用于std::unique的常量引用\u ptr<;B>;对象

C++ 为什么C2662错误没有';t适用于std::unique的常量引用\u ptr<;B>;对象,c++,c++11,constants,unique-ptr,C++,C++11,Constants,Unique Ptr,我理解以下错误C2662的原因。我的问题是为什么打电话 main()中的a.GetB()->Get()不会产生类似的错误,因为GetB()还会返回对唯一\u ptr对象的const引用 #include <iostream> #include <memory> using namespace std; class B { int i; public: B(int j) : i(j) {} int Get() { return i; }

我理解以下错误C2662的原因。我的问题是为什么打电话
main()
中的
a.GetB()->Get()
不会产生类似的错误,因为
GetB()
还会返回对
唯一\u ptr
对象的
const
引用

#include <iostream>
#include <memory>

using namespace std;

class B
{
    int i;

    public:
    B(int j) : i(j) {}
    int Get() { return i; }
};

class A
{
    std::unique_ptr<B> uptrB;

    public:
    A(int i) : uptrB(new B(i)) {}
    const std::unique_ptr<B>& GetB() { return uptrB; }
    const B* GetB1() { return uptrB.get(); }
};

int main()
{
    A a(3);
    cout << a.GetB()->Get() << endl;
    cout << a.GetB1()->Get() << endl;  // error C2662:'B::Get' cannot conver 'this' pointer from 'const B' to 'B&'
}
#包括
#包括
使用名称空间std;
B类
{
int i;
公众:
B(intj):i(j){}
int Get(){return i;}
};
甲级
{
std::唯一的ptr uptrB;
公众:
A(inti):uptrB(新B(i)){}
const std::unique_ptr&GetB(){return uptrB;}
常量B*GetB1(){return uptrB.get();}
};
int main()
{
A(3);

得不到
const std::unique\u ptr
类似于
B*const
,也就是说,指向可变
B
的不可变指针,而不是
const B*
,指向不可变
B
的不可变指针。如果您想从
unique\u ptr
版本中获得相同的错误,您需要按照是的,您通过
const
引用返回
unique\ptr
,但是它所引用的
B
不是
const

您从
getB()
方法返回一个const引用。您无法更改const引用指向的地址。但是调用
get()
返回的对象会给您指针。这不是一件好事情