Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of temporary bound to a member lifetime statement in C++ Standard?

In this question user Happy Mittal quotes section 12.2.5 of C++03 Standard: A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits.

How can that be useful anyway? I mean once the constructor exits the temporary gets destroyed, but the reference remains bound - now to an already destroyed object.

What's the point of so carefully specifying the temporary lifetime if there's still a dangling reference for the whole lifetime of the outer object? In which scenario can this behavior be useful?

like image 393
sharptooth Avatar asked Jan 18 '11 08:01

sharptooth


1 Answers

It is not useful to have a reference member bound to a dead object, but it is useful to be clear that "normal" temporary lifetime extension when bound to a reference doesn't apply in this case.

It also specifies temporary lifetime extension that applies specially in the ctor initializer: it's extended to the end of the ctor rather than dying before the ctor body executes. This would not be useful except in "clever" classes whose whole point is executing the ctor, and this type of (ab)use is rightly avoided.

I know of no real world examples of the latter, but it strikes me akin to having destructors nothrow by default broke classes that were "clever" in their lifetime and how they were used. This did have real world uses and came up in discussions about how to handle the default semantics of dtors in C++0x.

like image 183
Fred Nurk Avatar answered Oct 23 '22 04:10

Fred Nurk