Binding temporaries to const references
Hi,
I was playing around with const references and temporary objects to
make sure that I understood section 12.2. of the standard correctly.
My sample program has three cases A,B and C which bind a temporary
object to a const reference:
#include <iostream>
struct A
{
A(int i):
mInt(i)
{
}
~A()
{
std::cerr << "~A()" << std::endl;
}
int mInt;
private:
A(A const& other);
A& operator=(A const& other);
};
struct RefHolder
{
RefHolder():
mReference(A(1)) // A iso c++ 12.2.4
{
std::cerr << "RefHolder()" << std::endl;
}
RefHolder(A const& ref):
mReference(ref) // B iso c++ 12.2.4
{
std::cerr << "RefHolder(A const&)" << std::endl;
}
~RefHolder()
{
}
A const& mReference;
};
int main( int argc, char** argv )
{
{
A const& ref(A(2)); // C iso c++ 12.2.5
std::cerr << ref.mInt << std::endl;
}
{
RefHolder r;
int i = r.mReference.mInt;
std::cerr << i << std::endl;
}
{
RefHolder r(A(3));
std::cerr << r.mReference.mInt << std::endl;
}
return 0;
}
Compiled with gcc 4.4.1, this gives the following output (I know that
the object are destructed and that this undefined for the last two
cases):
2
~A()
~A()
RefHolder()
1
RefHolder(A const&)
~A()
3
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. Wouldn't it be reasonable to
have the same behaviour as in case C?
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]