简体   繁体   中英

move semantics behaviour on vector return

I've been playing around with c++11 move semantics

In the code...

#include <vector>
#include <string>

std::vector<std::string> GetNewVector()
{
  std::vector<std::string> newVec; 
  newVec.push_back(std::string("hello")); //(1)
  newVec.push_back(std::string("whey")); //(2)

  return newVec;
}

int main(int argc, char* argv[])
{
  std::vector<std::string> vec = GetNewVector();
}

At point (1) the move constructor for the "hello" object is called when the object is moved into the vector.

At point (2) firstly the move constructor for "hello" is called again, (I'm assuming this is where the vector reallocates) and then the "whey" move constructor is called.

This is all as expected, however I was expecting the objects to be moved again when the vector is returned at the end of GetNewVector() , however the move constructor doesn't get called again. My guess is that RVO is taking place however as I'm running Visual Studio (2k10) in Debug mode I wasn't sure if this would happen?

Is it true that if RVO can be performed, then it will take precedence over using the move constructor?

The advantages of moves on containers would be severly crippled if it was specified that they moved element-wise.

Instead, they simply take the others inner guts, the pointers to the dynamically allocated array in std::vector s case, which leaves the elements where they are, making this a constant complexity operation. If you did element-wise moves, you'd be looking at a linear complexity operation.

Is it true that if RVO can be performed, then it will take precedence over using the move constructor?

The standard is a bit restricted in this aspect, but yes, RVO (in general copy-elision, which also covers moves contrary to its name), will of course take precedence over anything else, since it's faster. :)

Note that automatic moves are only done in contexts where copy-elision could be done, but is not for whatever reason. See also this question for the more intricate details of automatic moves.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM