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?
return std::move(newVec)
. – Vaughn Catostd::move
here would inhibit RVO and the standard already says that the compiler first has to try to movenewVec
and only if that fails copy it. – Xeoreturn a_local_variable;
will already perform a move, if NRVO isn't applied. – Xeo