Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

9
  • 8
    but whats the use case for this ? Commented Oct 22, 2009 at 14:10
  • 26
    Well, s3_copy will create a temporary and then copy construct it into s3_copy whereas s3_reference directly uses the temporary. Then to be really pedantic you need to look at the Return Value Optimization whereby the compiler is allowed to elide the copy construction in the first case. Commented Oct 22, 2009 at 18:14
  • 7
    @digitalSurgeon: The magic there is quite powerful. The object lifetime is extended by the fact of the const & binding, and only when the reference goes out of scope the destructor of the actual referenced type (as compared to the reference type, that could be a base) is called. Since it is a reference, no slicing will take place in between. Commented Jan 14, 2010 at 17:06
  • 11
    Update for C++11: last sentence should read "You cannot bind a non-const lvalue reference to a temporary" because you can bind a non-const rvalue reference to a temporary, and it has the same lifetime-extending behaviour. Commented Nov 10, 2013 at 20:14
  • 9
    @AhmadMushtaq: The key use of this is derived classes. If there is no inheritance involved, you might as well use value semantics, which will be cheap or free due to RVO/move construction. But if you have Animal x = fast ? getHare() : getTortoise() then x will face the classic slicing problem, while Animal& x = ... will work correctly. Commented Nov 2, 2017 at 11:04