While asking this question, I learned const reference to a temporary object is valid in C++:
int main ()
{
int a = 21;
int b = 21;
//error: invalid initialization of non-const reference
//int & sum = a + b;e [...]
//OK
int const & sum = a + b;
return sum;
}
But in the following example, the const reference refnop
refers to a destroyed temporary object. I wonder why?
#include <string>
#include <map>
struct A
{
// data
std::map <std::string, std::string> m;
// functions
const A& nothing() const { return *this; }
void init() { m["aa"] = "bb"; }
bool operator!= (A const& a) const { return a.m != m; }
};
int main()
{
A a;
a.init();
A const& ref = A(a);
A const& refnop = A(a).nothing();
int ret = 0;
if (a != ref) ret += 2;
if (a != refnop) ret += 4;
return ret;
}
Tested using GCC 4.1.2 and MSVC 2010, it returns 4;
$> g++ -g refnop.cpp
$> ./a.out ; echo $?
4
The difference between ref
and refnop
is the call to nothing()
which does really nothing. It seems after this call, the temporary object is destroyed!
My question:
Why in the case of refnop
, the life time of the temporary object is not the same as its const reference?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…