Re: 'auto' and const references
On 5/3/2013 9:16 AM, Juha Nieminen wrote:
Let's say that a function returns a const reference. If I say this:
auto x = thatFunction();
what would the type of 'x' be? Will it be a const reference, thus
eliding copying, or will a copy be made?
I think the type should be the same as of the expression. If the
expression gives you the const ref, then 'x' will be a const ref and
will bind to the value returned by the function. Say, 'thatFunction' is
declared
const double& thatFunction();
then the type of 'x' is going to be const double&.
Is there any difference to these:
auto& x = thatFunction();
const auto& x = thatFunction();
Only if 'thatFunction' does not return a const ref.
The declaration 'auto' works essentially like a template type deduction.
The compiler needs to solve the "equation"
decltype(x) == decltype(thatFunction());
in which it will find out the "missing" parts that 'auto' will supply
when the declaration of 'x' is complete.
So, for instance, if 'thatFunction()' is like before,
decltype(x) == const double&
which gives you
const auto& == const double&
, you can drop the 'const', you can drop the '&', so you get that the
'auto' supplies 'double'. IOW, the declaration of 'x' will be the same as
const double& x
Now, take your example with 'auto& x = ', and you get
auto & x = const double &
you can drop the '&' (since it's the most inner specifier), so you get
'auto' to equal 'const double'. That doesn't change the fact that 'x'
is going to be a 'const double&', however.
Catch my drift?
V
--
I do not respond to top-posted replies, please don't ask