c++ - 自动类型推导和 auto&& 与 auto

标签 c++ c++11 rvalue-reference type-deduction

我刚刚看了 Scott Meyers Universal References in C++11有一件事我不太明白。

我对作为“通用引用”的 auto 之间的区别感到有点困惑,即 auto&& 和常规 auto,它们什么时候不同?

Foo f;
Foo& lvr = f;

auto lvr_a = f; // Foo&
auto rvr_a = std::move(f); // Foo&& or is it Foo?

auto&& lvr_b = f; // Foo& && => Foo&
auto&& lvr_b = std::move(f); // Foo&& && => Foo&&

最佳答案

auto 将衰减为值类型(即使用复制构造函数进行复制),而 auto&& 将保留引用类型。

参见此处:C++11: Standard ref for action of `auto` on const and reference types

auto rvr_a = std::move(f); // Foo&& or is it Foo?

它只是 Foo。所以这与:

Foo rvr_a = std::move(f); // Foo&& or is it Foo?

但请注意,如果有移动构造函数,它仍会调用移动构造函数。

关于c++ - 自动类型推导和 auto&& 与 auto,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12818432/

相关文章:

c++ - 如何在bitset上完成C++11编译时类静态成员初始化?

c++ - std::move 堆栈对象(到不同的线程)

c++ - 为什么在变量中存储右值引用会导致它悬空

c++ - 当价格 float 时对订单簿进行排序

c++ - WCHAR* 结尾包含垃圾

c++ - 当重载函数作为参数涉及时,模板参数推导如何工作?

C++11 Cereal 库无法序列化我的类

java - 在 C++ 中重新加载 Java 字符串

c++ - 类 : where to specify it? 函数的默认模板参数

c++ - 为什么 `auto&` 不能绑定(bind)到 volatile 右值表达式?