Do not return links, return value:
std::string function() // no ref { string s = "Faz"; s += "Far"; s += "Boo"; return s; }
If your compiler can perform named optimization of the return value, for example, NRVO (which is most likely), this will turn it into something roughly equivalent to the following, which avoids any extraneous copies:
// Turn the return value into an output parameter: void function(std::string& s) { s = "Faz"; s += "Far"; s += "Boo"; } // ... and at the callsite, // instead of: std::string x = function(); // It does this something equivalent to this: std::string x; // allocates x in the caller stack frame function(x); // passes x by reference
Regarding the additional question:
The line copy constructor always performs a deep copy. So, if there are copies, there is no problem with the alias. But when returning by value using NRVO, as you can see above, no copies are made.
You can create copies using several different syntaxes:
string orig = "Baz"; string copy1 = string(orig); string copy2(orig); string copy3 = orig;
The second and third have no semantic difference: they are both just initialized. The first creates a temporary value by explicitly invoking the copy constructor, and then initializes the variable with a copy. But the compiler can make a copy of elision here (and it is very likely that this will happen) and make only one copy.
source share