mercredi 1 juin 2016

const-reference binding to a temporary

Consider the following:

string const& name1 = get_name(...);
string const  name2 = get_name(...);

where get_name returns a string object. As is well known, with the introduction of move-semantics in C++11, both statements can be efficient, with the first one being slightly more so since a move does not need to be made. (Yeah, I know about return-value optimization, so it's slightly more nuanced. But this is the general idea.)

However, suppose function calls are left out of this:

string const& name3 {"Billy"};
string const  name4 {"Debbie"};

In this case, the string-literal "Billy" is implicitly converted to a temporary string, and name3 binds to the temporary. Obviously, name4 is not a temporary.

Is it true that for name3 and name4, both are equally efficient? Seems to me that it would be...

Aucun commentaire:

Enregistrer un commentaire