【问题标题】:Which is better to get return value, by const&, by &&, or just by value? [closed]通过 const&、&& 或仅通过值,哪个更好地获得返回值? [关闭]
【发布时间】:2021-09-05 10:28:22
【问题描述】:
#include <vector>

std::vector<int> f()
{
    return std::vector<int>(1024);
}

void use_1(std::vector<int> const&)
{}

void use_2(std::vector<int> const&)
{}

int main()
{
    {
        auto const& v = f(); // style 1
        use_1(v);
        use_2(v);
    }

    {
        auto&& v = f(); // style 2
        use_1(v);
        use_2(v);
    }

    {
        auto v = f(); // style 3
        use_1(v);
        use_2(v);
    }
}

哪个更好? 样式 1样式 2 还是 样式 3

在我看来,如果返回类型没有实现移动语义,那么 style 1style 2style 3 更高效 em>。

【问题讨论】:

  • (3) 是最直接的。 (1) 和 (2) 要求您了解延长寿命,这并不广为人知。
  • 为什么不std::vector&lt;int&gt; v = f();?您希望通过使用参考获得什么?
  • auto v = f(); 等价于std::vector&lt;int&gt; v = f()。 @463035818_is_not_a_number
  • “在我看来……样式 1 和样式 2 更有效” 不正确。 C++17 保证在您的返回中复制省略,这在早期标准的编译器中已经很常见。所有形式都同样有效。
  • 如果返回类型没有实现移动语义,就不要邀请它加入你的聚会。话虽如此,即使在这种情况下,它的效率也不会降低。

标签: c++ performance c++11 lifetime temporary-objects


【解决方案1】:

按值计算不会出错,而且效率也不低。生命是明确的,它永远不会悬空。参考版本容易出错。举个例子:

#include <utility>

struct Bar {};

template <class T>
auto&& foo(T&& t) {
  return std::forward<T>(t);
}

int main() { 
  auto&& bar = foo(Bar{});
  // bar dangles
}

您可能认为“这永远不会发生”,但随着代码库变得越来越复杂,它确实会发生。保持简单。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-10
    • 1970-01-01
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多