I was wondering if below code has any difference between #1, #2 and #3 when passing a string to a function (eg. insert into a vector). Especially when dealing with millions of strings in the code.
std::vector<std::string> v;
std::string s("foo");
int i = 1;
v.push_back( s + "bar" + boost::lexical_cast<std::string>(i) ); // #1
v.push_back( std::string(s + "bar" + boost::lexical_cast<std::string>(i)) ); // #2
std::string s2 = s + "bar" + boost::lexical_cast<std::string>(i);
v.push_back(s2); // #3
With a decent optimizer there should be no difference between #1 and #2, but #1 gives you the biggest chance that the compiler actually does temporary elimination.
However, #3 contains a named temporary, so it probably needs a great optimizer to detect that it’s just that – a temporary.