Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 what happens when a function returns

Tags:

c++

c++11

I'm wondering what happens when I have a function like this:

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;
}

what happens when the function returns?

Is 'temp' copied to a temporary r-value before being destroyed (out-of-scope) and with C++11 possibly NRVO-ptimized (so the copy of 'temp' is directly written to the return destination slot)?

like image 979
Paul Avatar asked Dec 05 '22 11:12

Paul


2 Answers

Nothing should be copied. There are two possibilities:

  • temp is moved to an object in the caller's scope; or
  • the move is elided, and temp becomes an alias for an object in the caller's scope. This is known as "return value optimisation".

Before 2011 (specifically, without move semantics), the first case would require a copy rather than a move. The second case was allowed in C++98 as well as 11.

like image 125
Mike Seymour Avatar answered Dec 25 '22 00:12

Mike Seymour


NRVO would mean that temp itself is constructed in the return value location. Without RVO, yes, temp is copied/moved from its location on the stack into the return value location prior to being destroyed.

like image 35
bames53 Avatar answered Dec 25 '22 00:12

bames53