C++ constant reference lifetime (container adaptor)

According to the C++03 standard, a temporary bound to a reference has differing lifetimes depending on the context. In your example, I think the highlighted portion below applies (12.2/5 “Temporary objects”):

The temporary to which the reference is bound or the temporary that is the complete object to a subobject of which the temporary is bound persists for the lifetime of the reference except as specified below. A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits. A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full expression containing the call.

So while binding a temporary is an advanced technique to extend the lifetime of the temporary object (GotW #88: A Candidate For the “Most Important const”), it apparently won’t help you in this case.

On the other hand, Eric Niebler has an article that you may be interested in that discusses an interesting (if convoluted) technique that could let your class’s constructors deduce whether a temporary object (actually an rvalue) has been passed to it (and therefore would have to be copied) or a non-temporary (lvalue) as been passed (and therefore could potentially safely have a reference stashed away instead of copying):

Good luck with it though – every time I read the article, I have to work through everything as if I’ve never seen the material before. It only sticks with me for a fleeting moment…

And I should mention that C++0x’s rvalue references should make Niebler’s techniques unnecessary. Rvalue references will be supported by MSVC 2010 which is scheduled to be released in a week or so (on 12 April 2010 if I recall correctly). I don’t know what the status of rvalue references is in GCC.

Leave a Comment