user3019338
user3019338

Reputation: 75

c++ "const T &const" What is the meaning of the 2nd const?

Could you please explain me the meaning of the second "const" in the following expression:

int i = 42;
const int &const ri = i;

Are there some cases where const T &const is mandatory?

What I understood so far: Pointers are objects, and they can be reassigned.

int i = 42;
const int *ptr1 = &i;        // valid: (low-level const): *ptr1 cannot be changed.
int *const ptr2 = &i;        // valid: (high-level const): ptr2 cannot be changed.
const int *const ptr3 = &i:  // also valid (combination of 2 precedent lines).

References, unliked pointers are not objects (they have no address) and cannot be reassigned ==> no meaning for an "high-level const"

int i = 42;
int &ri1 = i;        // valid: ri1 is a new name for i
const int &ri2 = 7;  // valid and const is required
const int &ri3 = i;  // valid, what is the use of const?

const int &const ri4 = i;  // valid, has the second const an importance? 

Upvotes: 0

Views: 401

Answers (1)

Mat
Mat

Reputation: 206699

The form int & const is ill-formed (C++11 §8.3.2):

In a declaration T D where D has either of the forms

& attribute-specifier-seqopt D1  
&& attribute-specifier-seqopt D1

and the type of the identifier in the declaration T D1 is “derived-declarator-type-list T,” then the type of the identifier of D is “derived-declarator-type-list reference to T.” The optional attribute-specifier-seq appertains to the reference type. Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef (7.1.3) or of a template type argument (14.3), in which case the cv-qualifiers are ignored.

So no, it can't be mandatory anywhere. And it has no semantics.

Upvotes: 1

Related Questions