当初始化程序是引用时,为什么auto不是引用?

时间:2012-07-01 04:43:32

标签: c++ c++11 standards

我试图理解为什么not_a_ref不是参考。我知道我可以通过auto &将其作为参考。我在标准中挖了一段时间,但迷路了,无法弄清楚这种行为的定义。

示例:

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

3 个答案:

答案 0 :(得分:5)

从C ++ 11草案,7.1.6.4(auto说明符)第6段:

  

根据函数调用(14.8.2.1),使用模板参数推导的规则确定推导出的变量d的类型是推导出的A.

从14.8.2.1(从函数调用中扣除模板参数)第3段:

  

如果P是引用类型,则P引用的类型用于类型推导。

因此,auto的类型推导忽略了引用。

请注意此规则与decltype的规则有何不同。

更新:请参阅下面的评论,因为我认为14.8.2.1第3段不适用。

答案 1 :(得分:3)

查看模板参数推断。 auto x = stuff;template<typename T> void f(T x) {} f(stuff);的类型相当x

答案 2 :(得分:-1)

根据C ++ 11标准,auto计为简单类型说明符[7.1.6.2],因此相同的规则适用于其他简单类型说明符。这意味着使用auto声明引用与其他任何内容都没有区别。

这意味着下一行:

auto not_a_ref = get_stuff();

将与:

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