问题
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?
回答1:
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.
回答2:
In D language, construction process can be written freely in some degree. However in C++, construction/initialization order is strictly stipulated. So if class initialization requires some expensive computation, a code like the following sometimes may be valid as a reluctant workaround.
struct S {
Args const &r;
A a;
B b;
S( args.... )
: r( expensive_func( args.... ) ), a( r.for_a ), b( r.for_b ) {}
};
回答3:
It's useful for compiler writers. They already have logic in place to destroy bound temporaries at the end of a scope, and the exit of the constructor is one such point. With this rule compilers can reuse that point to destroy such temporaries as well.
Note that the standard really should decide on some lifetime, and the only other reasonable point would be after the ctor initializer list but before the ctor body. That's not a point where temporaries would be destroyed otherwise, and it could interfere with function-scope try {} catch()
blocks (which do include the ctor initializer list)
来源:https://stackoverflow.com/questions/4721841/whats-the-point-of-temporary-bound-to-a-member-lifetime-statement-in-c-standa