GotW #2 Solution: Temporary Objects -- Herb Sutter

The solution to GotW #2 is now available:

GotW #2 Solution: Temporary Objects (updated for C++11/14)

by Herb Sutter

From the article:

Because C++ naturally enables move semantics for returned values like this string object, there’s usually little to be gained by trying to avoid the temporary when you return by value. ... For example, if the caller writes auto address = find_addr( mylist, “Marvin the Robot” );, there will be at most a cheap move (not a deep copy) of the returned temporary into address, and compilers are allowed to optimize away even that cheap move and construct the result into address directly.

But what if you did feel tempted to try to avoid a temporary in all return cases by returning a string& instead of string? Here’s one way you might try doing it that avoids the pitfall of returning a dangling reference to a local or temporary object: [...] To demonstrate why this is brittle, here’s an extra question:

For the above function, write the documentation for how long the returned reference is valid.

Go ahead, we’ll wait. ...

The questions for #3 are posted for discussion:

GotW #3: Using the Standard Library (or, Temporaries Revisited)

 

 

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.