自动类型扣除和自动与自动

Automatic type deduction and auto&& vs auto

本文关键字:类型      更新时间:2023-10-16

我刚刚在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:对常量和引用类型执行"auto"操作的标准引用

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

这只是Foo. 所以这和:

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

但请注意,如果有的话,这仍将调用移动构造函数。