#include <iostream>
using namespace std;
class X {
public :
X( ) { cout << " ctor " << this << endl; }
X( const X& ) { cout << " cpyctor " << this << endl; }
X operator+ ( X&& ) {
cout << " in +" << endl;
return X( ) ;
}
~X( ) { cout << " dtor " << this << endl; }
X& me( ) { cout << " yes!" << endl; return * this ; }
} ;
X f( ) {
cout << " in f" << endl;
return X( ) ; }
X& g( X& x) {
cout << " in g" << endl;
return x;
}
int main( ) {
cout << "case1 - completely safe: " << endl;
g( f( ) .me ( ) .me ( ) .me ( ) ) .me ( ) ;
cout << "end case1." << endl<< endl;
cout << "case2 - hoping for life extension but UB: " << endl;
{
X x;
{
X& myriskyref = ( x + f( ) ) .me ( ) ; // ouch!!! the temporary was created by operator/function return
// so no life extension accrdong to 12.2/5
cout << & myriskyref.me ( ) << endl;
} // permanent ref vanisches;
}
cout << "end case2." << endl<< endl;
cout << "case 3:" << endl;
{
const X donottouch;
//donottouch.me(); would be compilation error
}
cout << "end case 3." << endl;
return 0 ;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKY2xhc3MgWCB7CnB1YmxpYzogCiAgICBYKCkgeyBjb3V0PDwiICBjdG9yICI8PHRoaXM8PGVuZGw7IH0KICAgIFgoY29uc3QgWCYpIHsgY291dDw8IiAgY3B5Y3RvciAiPDx0aGlzPDxlbmRsOyB9CiAgICBYIG9wZXJhdG9yKyAoWCYmKSB7IAoJCWNvdXQ8PCIgICAgICAgICAgICAgICBpbiArIjw8ZW5kbDsKICAgIAlyZXR1cm4gWCgpOyAKICAgIH0KICAgIH5YKCkgeyBjb3V0PDwiICBkdG9yICI8PHRoaXM8PGVuZGw7IH0KICAgIFgmIG1lKCkgeyBjb3V0PDwiICAgIHllcyEiPDxlbmRsO3JldHVybiAqdGhpczsgfSAKfTsKClggZigpIHsgCgljb3V0PDwiICAgICAgICAgICAgICAgaW4gZiI8PGVuZGw7CglyZXR1cm4gWCgpOyB9ClgmIGcoWCZ4KSB7IAoJ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