当我使用 C++11 auto
时,关于解析为值还是引用,类型推导的规则是什么?
例如,有时很清楚:
auto i = v.begin(); // Copy, begin() returns an iterator by value
这些不太清楚:
const std::shared_ptr<Foo>& get_foo();
auto p = get_foo(); // Copy or reference?
static std::shared_ptr<Foo> s_foo;
auto sp = s_foo; // Copy or reference?
std::vector<std::shared_ptr<Foo>> c;
for (auto foo: c) { // Copy for every loop iteration?
最佳答案
规则很简单:就是你如何声明它。
int i = 5;
auto a1 = i; // value
auto & a2 = i; // reference
下一个例子证明了这一点:
#include <typeinfo>
#include <iostream>
template< typename T >
struct A
{
static void foo(){ std::cout<< "value" << std::endl; }
};
template< typename T >
struct A< T&>
{
static void foo(){ std::cout<< "reference" << std::endl; }
};
float& bar()
{
static float t=5.5;
return t;
}
int main()
{
int i = 5;
int &r = i;
auto a1 = i;
auto a2 = r;
auto a3 = bar();
A<decltype(i)>::foo(); // value
A<decltype(r)>::foo(); // reference
A<decltype(a1)>::foo(); // value
A<decltype(a2)>::foo(); // value
A<decltype(bar())>::foo(); // reference
A<decltype(a3)>::foo(); // value
}
输出:
value
reference
value
value
reference
value
关于C++11 "auto"语义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8542873/