fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class X {
  5. public:
  6. X() { cout<<" ctor "<<this<<endl; }
  7. X(const X&) { cout<<" cpyctor "<<this<<endl; }
  8. X operator+ (X&&) { return X(); }
  9. ~X() { cout<<" dtor "<<this<<endl; }
  10. X& me() { cout<<" yes!"<<endl;return *this; }
  11. };
  12.  
  13. X f() { return X(); }
  14. X& g(X&x) { return x; }
  15.  
  16. int main() {
  17. cout << "case1 - completely safe: "<<endl;
  18. g(f().me().me().me()).me();
  19. cout << "end case1."<<endl<<endl;
  20.  
  21. cout << "case2 - hoping for life extension but UB: "<<endl;
  22. {
  23. X x;
  24. {
  25. X& myriskyref = (x + f()).me(); // ouch!!! the temporary was created by operator/function return
  26. // so no life extension accrdong to 12.2/5
  27. cout << " ...next..."<<endl;
  28. cout << " OUCH!! temp already deleted (see above):"<<&myriskyref.me() <<endl;
  29. } // permanent ref vanisches;
  30. }
  31. cout << "end case2."<<endl<<endl;
  32. cout<< "case 3:" <<endl;
  33. {
  34. const X donottouch;
  35. //donottouch.me(); would be compilation error
  36. }
  37. cout << "end case 3."<<endl;
  38.  
  39. return 0;
  40. }
Success #stdin #stdout 0s 3464KB
stdin
Standard input is empty
stdout
case1 - completely safe: 
  ctor 0xbfc75e2f
    yes!
    yes!
    yes!
    yes!
  dtor 0xbfc75e2f
end case1.

case2 - hoping for life extension but UB: 
  ctor 0xbfc75e2d
  ctor 0xbfc75e2f
  ctor 0xbfc75e2e
    yes!
  dtor 0xbfc75e2e
  dtor 0xbfc75e2f
  ...next...
    yes!
  OUCH!! temp already deleted (see above):0xbfc75e2e
  dtor 0xbfc75e2d
end case2.

case 3:
  ctor 0xbfc75e2f
  dtor 0xbfc75e2f
end case 3.