In C++, if "int a = 3; int* p = &a;", then why is "const int* &pp = p" not allowed, but "const int* const &pp = p" is allowed?

Viewed 147

In C++, if:

int a = 3; 
int* p = &a; 

then why is

const int* &pp = p; 

not allowed, but

const int* const &pp = p; 

is allowed?

3 Answers

Given const int* &pp = p;, p has to be converted to const int* implicitly at first. But the converted const int* is a temporary, which can't be bound to lvalue-reference to non-const (like const int* &).

Temporary could be bound to lvalue-reference to const (like const int* const &) (and rvalue-reference), so const int* const &pp = p; works fine. And the lifetime of the temporary is extended to the lifetime of the reference pp.

when the const on * left,the const modifier the point dest,when the const on * right,the const modifier point, and you question,the addr of local var shoule be const.

The reason that the first conversion is not allowed is that it (subtly and unintuitively) breaks const-correctness. There's a discussion here. In short, the problem is this:

const int x;
int* p;
const int** q = &p;
*q = &x;
*p = 3;

If the third line was valid, the fourth line would set p to point to x (because *q is p), so *p = 3 would modify x, even though x is const.

The same problem occurs when the top-level modifier is a reference rather than a pointer.

You have to go all-or-nothing when modifying const qualifiers in multi-layered pointer types.

Related