Joseph D.
Joseph D.

Reputation: 12174

Why cv-qualification for a reference is ill-formed?

As per dcl.ref/1:

Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef-name

So I've tried:

int a = 1;
int& const r1 = a;

And got the error:

error: 'const' qualifiers cannot be applied to 'int&'

which is expected to prompt the diagnostic message.

However, I wanted to know why is it prohibited.

Is it only to prevent the accident of writing the code above when programmer actually means:

const int& r1 = a; // const reference to int

MAIN QUESTION

2) Or is there some deeper reason / practical examples why disallowing it is indeed beneficial?

Any thoughts?

Upvotes: 3

Views: 145

Answers (1)

iBug
iBug

Reputation: 37267

CV-qualifiers are valid for pointers:

int a;
int * const p = &a;

This applies to the pointer itself, not what it points to.

But since you can't change a reference after definition, there's no point in adding CV-Qs to references.

Upvotes: 5

Related Questions