了解返回值优化和返回临时值 - C++

请考虑这三个功能.

std::string get_a_string()
{
    return "hello";
}

std::string get_a_string1()
{
    return std::string("hello");
}

std::string get_a_string2()
{
    std::string str("hello");
    return str;
}

  1. RVO 是否适用于所有三种情况?
  2. 可以像上面的代码那样返回一个临时的吗?我相信这没问题,因为我是按值返回它,而不是返回对它的任何引用.

有什么想法吗?

推荐答案

在前两种情况下,将进行 RVO 优化.RVO 是旧功能,大多数编译器都支持它.最后一种情况就是所谓的 NRVO(命名为 RVO).这是 C++ 相对较新的特性.标准允许但不要求实现 NRVO(以及 RVO),但一些编译器支持它.

In two first cases RVO optimization will take place. RVO is old feature and most compilers supports it. The last case is so called NRVO (Named RVO). That's relatively new feature of C++. Standard allows, but doesn't require implementation of NRVO (as well as RVO), but some compilers supports it.

您可以在 Scott Meyers 的书 更有效的 C++.35 种改进程序和设计的新方法.

You could read more about RVO in Item 20 of Scott Meyers book More Effective C++. 35 New Ways to Improve Your Programs and Designs.

这里是一篇关于Visual C++ 2005 中的 NRVO.

Here is a good article about NRVO in Visual C++ 2005.

相关文章