开发者

C++ return type qualifiers heaven

开发者 https://www.devze.com 2023-02-09 19:55 出处:网络
It\'s hell actually. Can someone please explain in plain English why the below segments work or not? class Hey;

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 开发者_JS百科'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 .


The compiler doesn't see "Hey*" and "const Hey*" as the same so it doesn't want to convert the reference whereas he convert the const reference (similar to parameter conversion)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号