Wrt. the suggested duplicate "Is pass-by-value a reasonable default in C++11?" - neither the question there nor the answers there make any mention of the "universal-reference" constructor version, so I really fail to see the duplication. Consider reopening.
I am getting familiar with the move semantic, experimenting with it. Please take a look at this (compilable) piece of code:
#include <iostream>
#include <string>
struct my_str {
std::string s;
my_str(const std::string & str): s(str) { std::cout << " my_str parameter ctor" << std::endl; }
my_str(const my_str & o): s(o.s) { std::cout << " my_str copy ctor" << std::endl; }
my_str(my_str && o): s(std::move(o.s)) { std::cout << " my_str move ctor" << std::endl; }
};
template <typename T>
my_str build_ur(T && s) {
return my_str(std::forward<T>(s));
}
my_str build_val(my_str s) {
return my_str(std::move(s));
}
int main() {
my_str s1("hello");
my_str s2("world");
std::cout << "Building from universal reference (copy):" << std::endl;
build_ur(s1);
std::cout << "Building from universal reference (move):" << std::endl;
build_ur(std::move(s1));
std::cout << "Building from value (copy):" << std::endl;
build_val(s2);
std::cout << "Building from value (move):" << std::endl;
build_val(std::move(s2));
std::cout << std::endl;
return 0;
}
Output:
g++-4.8 -std=c++11 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
my_str parameter ctor
my_str parameter ctor
Building from universal reference (copy):
my_str copy ctor
Building from universal reference (move):
my_str move ctor
Building from value (copy):
my_str copy ctor
my_str move ctor
Building from value (move):
my_str move ctor
my_str move ctor
http://coliru.stacked-crooked.com/a/3be77626b7ca6f2c
Both the functions do the right job in both cases. The by-value function calls the move constructor once more, which however should be cheap. Could you comment on situations in which one pattern should be preferred to the other?