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).
The type of 42
is int
, not const int
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With