Tuesday, April 10, 2012

why the reference of temporary object is valid here?

#include <iostream>
#include <string>
using namespace std;
class test
string a;
test(string b){a=b;}
friend string operator+(test);
string operator+(string &c,test a)
return c;
void main()
test d("the ");
test e("world!");
string s="Hello ";

the second last line s=s+d+e; after the fist overloaded operator + it returned a temporary object,and the second overloaded operator + unexpectedly worked!But the first parameter of operator+ function is a reference. why the reference of temporary object is valid here,or there is something i have missed?

P.S: It's compiled by VC++6.0 and here is the running result.enter image description here

1 comment:

  1. Temporary objects last until the end of the full-expression in which they are created - roughly speaking, until the ; at the end of the line. References to them are valid until that point.

    However, it's not valid to bind it to a non-const reference as you do. The only reason that compiles is because your compiler is over 15 years old, and the language has been through two major changes since then. I suggest you upgrade to one of this millenium's compilers.