gpt4 book ai didi

c++ - 为什么 auto 的初始值设定项是引用时不是引用?

转载 作者:可可西里 更新时间:2023-11-01 16:38:55 26 4
gpt4 key购买 nike

我试图理解为什么 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;
}

最佳答案

来自 C++11 草案,7.1.6.4(auto 说明符)第 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).

从 14.8.2.1(从函数调用中推导出模板参数)第 3 段:

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

因此对于 auto 的类型推导,引用只是被忽略了。

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

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

关于c++ - 为什么 auto 的初始值设定项是引用时不是引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11279647/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com