C++ 11函数返回时会发生什么

Pau*_*aul 4 c++ c++11

我想知道当我有这样的函数时会发生什么:

typedef std::unordered_map<std::string,std::string> stringmap;

stringmap merge (stringmap a,stringmap b) 
{
  stringmap temp(a); temp.insert(b.begin(),b.end()); return temp;
}
Run Code Online (Sandbox Code Playgroud)

函数返回时会发生什么?

'temp'是否在被销毁之前复制到临时r值(超出范围)并且C++ 11可能是NRVO-ptimized(因此'temp'的副本直接写入返回目标槽)?

Mik*_*our 7

什么都不应该复制.有两种可能性:

  • temp被移动到调用者范围内的对象; 要么
  • 移动被省略,并temp成为调用者范围内对象的别名.这被称为"返回值优化".

在2011年之前(具体而言,没有移动语义),第一种情况需要复制而不是移动.第二种情况允许在C++ 98和11中使用.


bam*_*s53 5

NRVO意味着它temp本身是在返回值位置构建的.没有RVO,是的,temp在被销毁之前从堆栈中的位置复制/移动到返回值位置.