Zac
Zac

Reputation: 3285

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;
}

Upvotes: 9

Views: 388

Answers (3)

rodrigo
rodrigo

Reputation: 98526

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.

Upvotes: 5

BЈовић
BЈовић

Reputation: 64293

According to the C++11 standard, auto counts as a simple-type-specifier [7.1.6.2], therefore the same rules apply to it as to other simple-type-specifiers. This means that declaring references with auto is no different from anything else.

This means next line :

auto not_a_ref = get_stuff();

is going to be the same as :

std::vector<int> not_a_ref = get_stuff();

Upvotes: -1

Puppy
Puppy

Reputation: 147056

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.

Upvotes: 3

Related Questions