Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this `auto` not automatically turn into "`const`" [duplicate]

Tags:

c++

Possible Duplicate:
auto reference in c++11

The more I learn C++, the more I have come to realize that so far (almost; see below) everything in it basically just makes sense. I find that I don't really have to learn any rules by heart because everything behaves as expected. So the main thing becomes to actually understand the concepts, and then the rest takes care of itself.

For instance:

const int ci = 0;
auto &a = ci;       //automatically made const (const int &)

This works and makes sense. Anything else for the type of a would just be absurd.

But take these now:

auto &b = 42;       //error -- does not automatically become const (const int)
const auto &c = 42; //fine, but we have to manually type const

Why is the first an error? Why doesn't the compiler automatically detect this? Why does the const have to be typed out manually? I want to really understand why, on a fundamental level so that things make sense, without having to learn any rigid rules by heart (see above).

like image 973
Dennis Ritchie Avatar asked Dec 06 '22 10:12

Dennis Ritchie


2 Answers

The type of 42 is int, not const int.

like image 153
RichieHindle Avatar answered Dec 09 '22 14:12

RichieHindle


The auto keyword in C++11 behaves very close to how template type deduction works (going back to your concepts approach). If you state the type deduction in terms of template argument deduction it becomes more apparent (I believe):

template <typename T>
void f(T);
template <typename T>
void g(T&);

const int i;
f(i);              --> T deduced to be int
g(i);              --> T deduced to be const int

Basically you are creating a new variable initialized with an existing variable. Const-ness of the original from which you copy is orthogonal to const-ness of the destination object.

like image 26
David Rodríguez - dribeas Avatar answered Dec 09 '22 13:12

David Rodríguez - dribeas