Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is auto not a reference when its initializer is a reference?

I'm trying to understand why not_a_ref is not a reference. I understand that I can make it a reference by auto &. I dug around in the standard for awhile, but got lost and couldn't figure out where this behaviour is defined.

Example:

#include <vector>
#include <iostream>
#include <type_traits>

std::vector<int> stuff;

std::vector<int>& get_stuff()
{
    return stuff;
}

int main()
{
    auto not_a_ref = get_stuff();

    if( std::is_reference<decltype(not_a_ref)>::value )
        std::cout << "is_reference true" << std::endl;
    else
        std::cout << "is_reference false" << std::endl;

    if( &not_a_ref != &stuff )
        std::cout << "definately not a reference" << std::endl;

    return 0;
}
like image 333
Zac Avatar asked Jul 01 '12 04:07

Zac


2 Answers

From C++11 draft, 7.1.6.4 (auto specifier) paragraph 6:

The type deduced for the variable d is then the deduced A determined using the rules of template argument deduction from a function call (14.8.2.1).

And from 14.8.2.1 (Deducing template arguments from a function call) paragraph 3:

If P is a reference type, the type referred to by P is used for type deduction.

So the reference is just ignored for the type deduction of auto.

Note how this rule is different from that of decltype.

UPDATE: Please see my comment below, as I think 14.8.2.1 paragraph 3 does not apply.

like image 192
rodrigo Avatar answered Nov 12 '22 18:11

rodrigo


Have a look at template argument deduction. auto x = stuff; is quite equivalent to template<typename T> void f(T x) {} f(stuff); inso far as the type of x.

like image 28
Puppy Avatar answered Nov 12 '22 19:11

Puppy