Cannot initialize non-const reference from convertible type

I cannot initialize a non-const reference for type T1 from convertible type T2. However, I can use the const link .

long l;
const long long &const_ref = l; // fine
long long &ref = l;             // error: invalid initialization of reference of
                                // type 'long long int&' from expression of type
                                // 'long int'

Most of the problems I ran into were related to r values ​​that cannot be assigned to a non-constant reference. Not so here - can anyone explain? Thank.

+3
source share
4 answers

Integer promotion results in an rvalue value. longcan be raised to long long, and then snapped to a constant reference. As if you did:

typedef long long type;
const type& x = type(l); // temporary!

, r, , . ( , long long .)

+7

long long , long, . long long long . , , .

:

long a = 0; 
long long b = 0;

a = b; // works!

long *pa = 0;
long long *pb = pa;

. , , , , , . ,

struct A { long i; };
struct B { long long i; };

A a;
B b = a; // fail!

A B long long long , long& long long&, . - . .

, , , .

+1

, , , long long long. , l. l, .

0

Suppose this is possible:

 long long &ref = l; 

This means that later in the code, you can change the value referenced by ref to a value that is larger than the long type but can be long. In practice, this means that you are overwriting extra bytes of memory that can be used by another variable with unpredictable results.

0
source

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


All Articles