It's hell actually. Can someone please explain in plain English why the below segments work or not?
class Hey;
class Bitmap {
public:
const Hey* const& getHey() { return hey; }; // works
const Hey* & getHey2() { return hey; }; // error C2440: 'return' : cannot convert from 'Hey *' to 'const Hey *&'
private:
Hey* hey;
};
You can't add const
to a pointer more than one type deep which is not itself const
, because then you could stuff the address of a const
variable into a non-const
pointer. Consider:
char c;
char* p = &c;
const char* cp = p; // ok, only one type deep
const char x;
cp = &x; // ok
const char*& r = p; // fail, because...
r = cp; // ok
*p = 5; // ok, would overwrite a const variable if binding r to p were allowed
Making the pointer const
prevents this disaster a different way. Continuing the example:
const char* const& cr = p; // ok
cr = cp; // fail, cr is const, saving us from...
*p = 5; // would overwrite a const variable if cr = cp were allowed
A const reference can be initialized to an object of a different type or to an rvalue , such as a constant expression:
const int i = 42;
// legal for const references only
const int &r = i;
The same initializations are not legal for nonconst references.
You are trying to initialize reference with const expression. Const expression is rvalue. The const reference can be initialize with rvalue, while non const can't.
Edit: About rvalues and lvalues you can read in weakipedia .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With