Reputation: 1103
In this code:
int a=8;
const int &b = a; //b is a Low-Level const
auto c = b;
I expected c
to be constant int type since it has been auto
ed to a low level const. But it is referring to a
(which has been aliased by b
) instead if b
for its declaration.
c
picks the b
's type only when it is used like auto &c =b
What I understand is only top-level const is dropped. So can someone please explain what is wrong with my understanding?
Whereas in case of a pointer, the low level const is picked by auto
:
int i=9;
const int * p=&i;
auto *d=p;
*d=45; // error: assignment of read-only location ‘* d’
.
Upvotes: 0
Views: 62
Reputation: 141618
The type of an expression is never a reference type. Expressions have non-reference types, and value categories.
The declaration const int &b = a;
means:
b
.b
has type const int
.b
designates the same object as a
. In other words, the names a
and b
both refer to the same object.decltype(b)
resolves to const int&
, but apart from that, you can't access the "history" of a reference. Once it's been bound, it's just a name for an int thereafter.auto c = X;
means that c
is not declared as a reference; and its type is deduced from the the type of the expression X
. If X
happens to be the identifier of a variable, that does NOT invoke any special rules; X
is treated as an expression in all cases.
The syntax decltype(auto) C = X;
exists; if X is the name of a variable then this means that C is declared in the same way as X. (If X is not the name of a variable then the behaviour depends on the value category of X too).
In your first example, c
is deduced from the type of the expression b
which is const int
. As you noted, top-level const is dropped here, so auto c
means int c
.
In your second example, the type of the expression p
is const int *
. This is not a top-level const, so auto d = p;
would be const int * d = p;
. In this case auto *d
is not different to auto d
.
Upvotes: 3
Reputation: 1698
In the first example b and a are linked however c becomes the constant, this is because of the const in b taking effect. The problem with the second example is that *d is type const int which cannot be modified.
Hope this helps.
Upvotes: 0
Reputation: 26050
Auto uses the template type deduction rules. The long and the short of it is that references get dropped when using auto
(which is the reason you'll see things like decltype(auto)
as returns for functions, as this uses a different set of rules for type deduction).
Scott Meyers goes through the rules in some detail in Item 2 of Effective Modern C++.
Upvotes: 3