c++ - RVO应该什么时候启动?

标签 c++ return-value return-value-optimization

从下面的代码来看,如果发生了 RVO,我希望看到 2 个地址指向同一个位置,但事实并非如此(我的编译器是 MS VC9.0)

#include <iostream>
#include <string>

std::string foo(std::string& s)
{
   std::cout << "address: " << (unsigned int)(&s) << std::endl;
   return s;
}

int main()
{
   std::string base = "abc";
   const std::string& s = foo(base);
   std::cout << "address: " << (unsigned int)(&s) << std::endl;
   std::cout << s << std::endl;
   return 0;
}

RVO 应该在什么条件下发生?

顺便说一句,我的问题基于以下讨论:http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/

最佳答案

RVO 通常在您返回一个未命名的临时对象时适用,但如果您返回一个以前创建的对象,则

std::string foo() {
  return std::string("hello world"); // RVO
}

std::string foo() {
  std::string str("hello world");
  bar();
  return str; // Not RVO
}

std::string foo(std::string str) {
  return str; // Not RVO
}

一个更通用的版本是 NRVO(命名返回值优化),它也适用于命名变量。

std::string foo() {
  std::string str("hello world");
  bar();
  return str; // NRVO
}

std::string foo(std::string str) {
  return str; // Not NRVO, as far as I know. The string is constructed outside the function itself, and that construction may be elided by the compiler for other reasons.
}

std::string foo(std::string str) {
  std::string ret;
  swap(ret, str);
  return ret; // NRVO. We're returning the named variable created in the function
}

关于c++ - RVO应该什么时候启动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2025899/

相关文章:

c++ - 返回值复制问题(以改进调试时间)——这里的解决方案是什么?

c++ - 检测 CPU 架构编译时

C++ 单行注释后跟\transforms 在多行注释中

c++ - 始终返回的地址为0而不是实际值

arrays - 将数组从 ActiveX 组件返回到 JavaScript

c - 函数指针疑问

c++ - 信任返回值优化

c++ - 类内部定义的结构

c++ - 具有相同名称的类 - 是否仅限于同一翻译单元?

c++ - 什么是复制省略和返回值优化?