Is their any reason why the below code does not perform copy elision during copy initialization when the std::string is passed by value, but performs it if passed by const reference.
The below code was tested on Visual Studio Express 2012 Update 4 and Visual Studio 2013 Professional Update 2.
I stumbled upon this after thinking about the pass by value and move into place idiom suggested at last years going native conference and by various blogs (such as herb sutter's and cpp-next want speed pass by value).
Example code that does NOT perform copy elision.
#include <string>
#include <iostream>
using std::cout;
using std::endl;
using std::string;
class Object {
public:
Object(string name)
: _name{move(name)} {
cout << "Object(string)" << endl;
}
Object(Object&& other)
: _name{move(other._name)} {
cout << "Object(Object&&)" << endl;
}
Object(const Object& other)
: _name{other._name} {
cout << "Object(const Object&)" << endl;
}
private:
string _name;
};
int main(int argc, char* argv[]) {
auto name = string{"Object"};
auto obj = Object{name};
return 0;
}
Output:
Object(string)
Object(Object&&)
Example code that DOES perform copy elision.
#include <string>#include <iostream>
using std::cout;
using std::endl;
using std::string;
class Object {
public:
Object(const string& name)
: _name{name} {
cout << "Object(const string&)" << endl;
}
Object(Object&& other)
: _name{move(other._name)} {
cout << "Object(Object&&)" << endl;
}
Object(const Object& other)
: _name{other._name} {
cout << "Object(const Object&)" << endl;
}
private:
string _name;
};
int main(int argc, char* argv[]) {
auto name = string{"Object"};
auto obj = Object{name};
return 0;
}
Output:
Object(const string&)
Any feedback is appreciated :)