C ++ type selection criteria

This is actually hell. Can someone explain in plain English why the lower segments work?

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; }; 
+4
source share
3 answers

You cannot add const to a pointer to more than one type, which is not const , because then you can fill the address of the variable const pointer not const . 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 

Creating a const pointer prevents this catastrophe in 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 
+8
source

A reference to a constant can be initialized by an object of another type or by the value of r, for example, with 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 a link using a const expression. The expression Const is the value of r. A reference to a constant can be initialized using rvalue, but not const.

Change About the meanings and meanings you can read in weakipedia .

+1
source

The compiler does not see "Hey *" and "const Hey *" as the same, so it does not want to convert the link, while it converts a constant link (similar to parameter conversion)

0
source

Source: https://habr.com/ru/post/1338854/


All Articles