The following code, compiled on VS2013, never invokes std::string's move constructor (checked via setting breakpoints, the const ref copy constructor is invoked instead.
#include <iostream>
#include <string>
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
struct foo
{
foo(std::string& str1, std::string& str2) : _str1(str1), _str2(str2) {}
~foo() { std::cout << "Either \"" << _str1 << "\" or \"" << _str2 << "\" was returned." << std::endl; }
std::string& _str1;
std::string& _str2;
};
std::string foobar()
{
std::string str1("Hello, World!");
std::string str2("Goodbye, cruel World.");
foo f(str1, str2);
srand(time(NULL));
return (rand() % 2) ? str1 : str2;
}
int main()
{
std::cout << "\"" << foobar() << "\" was actually returned." << std::endl;
return EXIT_SUCCESS;
}
I would expect the return statement in foobar() to invoke the move constructor since I'm returning a local (the rand() is to prevent NRVO), like stated as answers to questions such as Returning std::move of a local variable
The context of this is that I'm trying to add another example for my other question here: https://softwareengineering.stackexchange.com/questions/258238/move-semantics-in-c-move-return-of-local-variables