【问题标题】:Automatic type deduction and auto&& vs auto自动类型推断和 auto&& vs auto
【发布时间】:2012-10-10 11:38:15
【问题描述】:

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

我对@9​​87654322@ 作为“通用参考”(即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&&

【问题讨论】:

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


    【解决方案1】:

    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?
    

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    • 2020-04-22
    • 1970-01-01
    相关资源
    最近更新 更多