Matthias Hofmann
2003-12-11 21:21:27 UTC
Hello,
I have just read a book about common errors in C++ programs. The following
code demonstrates the error:
const int& max( const int& i1, constint& i2 )
{
return i1 > i2 ? i1 : i2;
}
void f()
{
const int& i = max( 2, 3 );
std::cout << i << std::endl;
}
The book states that a temporary object is created for each parameter to
max(), and that a reference to one of these temporary objects is returned.
However, the book also states that the temporaries will both be destroyed
right after the call to max(), thus creating a dangling reference.
I remember to have read something in the standard that says that the
lifetime of the temporary object is extended to the lifetime of the
reference that is initialized with it, but I am not quite sure.Can anyone
please clarify this for me and tell me wether the book is correct or not?
Best regards,
Matthias Hofmann
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
I have just read a book about common errors in C++ programs. The following
code demonstrates the error:
const int& max( const int& i1, constint& i2 )
{
return i1 > i2 ? i1 : i2;
}
void f()
{
const int& i = max( 2, 3 );
std::cout << i << std::endl;
}
The book states that a temporary object is created for each parameter to
max(), and that a reference to one of these temporary objects is returned.
However, the book also states that the temporaries will both be destroyed
right after the call to max(), thus creating a dangling reference.
I remember to have read something in the standard that says that the
lifetime of the temporary object is extended to the lifetime of the
reference that is initialized with it, but I am not quite sure.Can anyone
please clarify this for me and tell me wether the book is correct or not?
Best regards,
Matthias Hofmann
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]