为什么C2662错误没有't应用于对std::unique_ptr<B>对象

Why the C2662 error doesn't apply to a const reference to a std::unique_ptr<B> object?

本文关键字:unique 对象 ptr lt std gt 应用于 错误 C2662 为什么      更新时间:2023-10-16

我理解下面指出的错误C2662的原因。我的问题是为什么打电话
main()中的a.GetB()->Get()不会产生类似的错误,因为GetB()还返回了对unique_ptr<B>对象的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&'
}

const std::unique_ptr<B>类似于B* const,即指向可变B的不可变指针,而不是指向不可变B的可变指针const B*。如果您想从unique_ptr版本中得到相同的错误,则需要编写std::unique_ptr<const B>。实际上,您是通过const引用返回unique_ptr,但它所引用的B不是const

您正在从getB()方法返回一个const引用。不能更改常量引用所指向的地址。然而,对返回的对象调用get()会得到指针。这不是一件好事!