C++11 "auto"语义
C++11 "auto" semantics
当我使用c++ 11 auto
时,关于它将解析为值还是引用的类型推导规则是什么?
E。G,有时候很明显:
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
§7.1.6.4 [dcl.spec.auto] p6
一旦根据8.3确定了声明符id的类型,使用声明符id声明的变量的类型将使用模板参数推导规则从其初始化器的类型确定。
这意味着auto
在函数调用期间建模模板参数推导。
template<class T>
void f(T){} // #1, will also be by-value
template<class T>
void g(T&){} // #2, will always be by-reference
注意#1将始终复制传递的实参,无论传递的是引用还是其他参数。(除非您特别指定模板参数,如f<int&>(intref);
)
无论你从右边(of "=")得到什么都不是引用。更具体地说,表达式的结果永远不是引用。在这种情况下,请注意示例中结果之间的差异。
#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()
{
auto a3 = bar();
A<decltype(bar())>::foo(); // reference
A<decltype(a3)>::foo(); // value
}
相关文章:
- 何时在引用或唯一指针上使用移动语义
- 如何从具有移动语义的类对象中生成共享指针
- Boost Spirit,获取迭代器内部语义动作
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 可以使用移动语义更改或改进此C++代码吗?
- c++在使用指针时移动语义
- 如何在自定义类中启用'auto loops'?
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 在C++17中,引用const字符串的语义应该是什么
- Xcode 语义问题引用或以前定义的代码
- 使用移动和复制语义时函数匹配如何工作?
- 为什么当我为 for(auto& it : myUnorderedMap) {... = std::move(it.second)} 时,我会得到一个 const 引用?
- 将向量从 N1 缩小到 N2 项,而不触发默认构造函数并仅使用 move 语义
- 为什么结构化绑定不使用"auto&"返回对结构成员的引用,而是返回成员本身
- 擦除许多矢量元素,同时使用'auto'
- 考虑到其他好处,关键字'auto'真的有助于简化调试C++吗?
- 为什么"weak.lock()"返回"nullptr" "auto weak=std::make_shared<int>(42);"的定义?
- 移动语义和深层/浅层复制之间有什么关系?
- 了解构造函数在移动、复制、赋值语义中的行为
- C++11 "auto"语义