I understand the reason for the error C2662 indicated below. My question is why the call
a.GetB()->Get() in main() doesn’t incur in a similar error, as GetB() also returns a const reference to a unique_ptr<B> object ?
#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>is analogous toB* const, that is, an immutable pointer to a mutableB—notconst B*, a mutable pointer to an immutableB. If you wanted to get the same error from theunique_ptrversion, you would need to writestd::unique_ptr<const B>. As it is, you are returning theunique_ptrbyconstreference, but theBto which it refers is notconst.