c++ - 为什么 Visual Studio 在这种情况下不执行返回值优化 (RVO)

标签 c++ c++11 visual-studio-2013 move-semantics rvo

我在回答 a question并推荐return by-value for a large type因为我确信编译器会执行 return-value optimization (RVO) .但后来有人向我指出,Visual Studio 2013 没有在我的代码上执行 RVO。

我找到了a question here关于 Visual Studio 未能执行 RVO,但在这种情况下,结论似乎是,如果它真的很重要,Visual Studio 将执行 RVO。就我而言,它确实很重要,它会对性能产生重大影响,我已经通过分析结果证实了这一点。这是简化的代码:

#include <vector>
#include <numeric>
#include <iostream>

struct Foo {
  std::vector<double> v;
  Foo(std::vector<double> _v) : v(std::move(_v)) {}
};

Foo getBigFoo() {
  std::vector<double> v(1000000);
  std::iota(v.begin(), v.end(), 0);  // Fill vector with non-trivial data

  return Foo(std::move(v));  // Expecting RVO to happen here.
}

int main() {
  std::cout << "Press any key to start test...";
  std::cin.ignore();

  for (int i = 0; i != 100; ++i) {  // Repeat test to get meaningful profiler results
    auto foo = getBigFoo();
    std::cout << std::accumulate(foo.v.begin(), foo.v.end(), 0.0) << "\n";
  }
}

我希望编译器对 getBigFoo() 的返回类型执行 RVO。但它似乎是在复制 Foo

我知道编译器 will create a copy-constructor对于 Foo。我也知道与兼容的 C++11 编译器不同 Visual Studio does not create a move-constructor对于 Foo。但这应该没问题,RVO 是一个 C++98 概念,无需 move 语义即可工作。

那么,问题是,Visual Studio 2013 在这种情况下不执行返回值优化是否有充分的理由?

我知道一些解决方法。我可以为 Foo 定义一个 move 构造函数:

Foo(Foo&& in) : v(std::move(in.v)) {}

这很好,但是有很多遗留类型没有 move 构造函数,很高兴知道我可以依赖 RVO 来处理这些类型。此外,某些类型可能本质上是可复制的,但不可 move 。

如果我从 RVO 更改为 NVRO(命名返回值优化),那么 Visual Studio 确实 似乎会执行优化:

  Foo foo(std::move(v))
  return foo;

这很好奇,因为我认为 NVRO 的可靠性不如 RVO。

更奇怪的是,如果我更改 Foo 的构造函数,使其创建并填充 vector:

  Foo(size_t num) : v(num) {
    std::iota(v.begin(), v.end(), 0);  // Fill vector with non-trivial data
  }

当我尝试做 RVO 时,它没有将其移入,而是有效:

Foo getBigFoo() {
  return Foo(1000000);
}

我很高兴采用其中一种解决方法,但我希望能够预测 RVO 将来何时可能会像这样失败,谢谢。

编辑: More concise live demo来自@dyp

Edit2:我为什么不直接写return v;

首先,它没有帮助。 Profiler 结果显示,如果我只编写 return v;,Visual Studio 2013 仍会复制 vector ,即使它确实有效,也只是一种解决方法。我并没有试图真正修复这段特定的代码,我试图理解 RVO 失败的原因,以便我可以预测它将来何时可能失败。确实,这是编写此特定示例的一种更简洁的方式,但是在很多情况下我不能只编写 return v;,例如 if Foo有额外的构造函数参数。

最佳答案

如果代码看起来应该优化,但没有得到优化,我会在这里提交错误 http://connect.microsoft.com/VisualStudio或向 Microsoft 提出支持案例。 这篇文章虽然是针对 VC++2005 的(我找不到当前版本的文档),但它确实解释了一些它不起作用的场景。 http://msdn.microsoft.com/en-us/library/ms364057(v=vs.80).aspx#nrvo_cpp05_topic3

如果我们想确定优化已经发生,一种可能性是检查汇编输出。如果需要,这可以作为构建任务自动化。

这需要使用/FAs 选项生成 .asm 输出,如下所示:

cl test.cpp /FAs

会生成test.asm。

下面 PowerShell 中的一个潜在示例,可以这样使用:

PS C:\test> .\Get-RVO.ps1 C:\test\test.asm test.cpp
NOT RVO test.cpp - ; 13   :   return Foo(std::move(v));// Expecting RVO to happen here.

PS C:\test> .\Get-RVO.ps1 C:\test\test_v2.optimized.asm test.cpp
RVO OK test.cpp - ; 13   :   return {std::move(v)}; // Expecting RVO to happen here.

PS C:\test> 

脚本:

# Usage Get-RVO.ps1 <input.asm file> <name of CPP file you want to check>
# Example .\Get-RVO.ps1 C:\test\test.asm test.cpp
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,Position=1)]
  [string]$assemblyFilename,

  [Parameter(Mandatory=$True,Position=2)]
  [string]$cppFilename
)

$sr=New-Object System.IO.StreamReader($assemblyFilename)
$IsInReturnSection=$false
$optimized=$true
$startLine=""
$inFile=$false

while (!$sr.EndOfStream)
{
    $line=$sr.ReadLine();

    # ignore any files that aren't our specified CPP file
    if ($line.StartsWith("; File"))
    {
        if ($line.EndsWith($cppFilename))
        {
            $inFile=$true
        }
        else
        {
            $inFile=$false
        }
    }

    # check if we are in code section for our CPP file...
    if ($inFile)
    {
        if ($line.StartsWith(";"))
        {
            # mark start of "return" code
            # assume optimized, unti proven otherwise
            if ($line.Contains("return"))
            {
                $startLine=$line 
                $IsInReturnSection=$true
                $optimized=$true
            }
        }

        if ($IsInReturnSection)
        {
            # call in return section, not RVO
            if ($line.Contains("call"))
            {
                $optimized=$false
            }

            # check if we reached end of return code section
            if ($line.StartsWith("$") -or $line.StartsWith("?"))
            {
                $IsInReturnSection=$false
                if ($optimized)
                {
                    "RVO OK $cppfileName - $startLine"
                }
                else
                {
                    "NOT RVO $cppfileName - $startLine"
                }
            }
        }
    }

}

关于c++ - 为什么 Visual Studio 在这种情况下不执行返回值优化 (RVO),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25963685/

相关文章:

c++ - 处理输入流运算符中的无效输入>>

c++ - gnu c++0x 向后兼容状态 - 我可以打开它然后继续吗?

android - 无法在 visual studio 的 apache cordova 中更改已安装的 android 平台

c++ - Windows 脚本宿主在关闭创建的窗口时终止

c++ - 使用 DELETE 来节省内存,有人可以证明

android - 如何在 Android Studio 3.1.2 中添加原生 OpenCV?

c++ - 获得所需的最少射门次数,以便进球数超过射门数是给定的百分比

c++ - C++ 中的无休止循环,比较两个字符

c++ - Visual Studio 2013 在文件 "C:\Program Files (x86)\Windows Kits\8.1\Include"中给出错误

c++ - Visual Studio 错误的自动完成功能