// MT3Q2.cpp - what happens when? #include #include class X { public: X() { pStr = new std::string("default x"); std::cout << "\n X constructed"; } X(const X& x) { pStr = new std::string(*(x.pStr)); std::cout << "\n X copied"; } ~X() { delete pStr; std::cout << "\n X destroyed"; } void take(std::string str) { delete pStr; pStr = new std::string(str); } const std::string say() { return *pStr; } X& operator=(const X& x) { if(&x == this) return *this; delete pStr; pStr = new std::string(*(x.pStr)); std::cout << "\n X assigned"; return *this; } private: std::string* pStr; }; X SomeFunction1(void) { // return value optimization will eliminate // the copy in call below return X(); } X SomeFunction2(void) { // no return value optimization here // so you see the copy operation X x; x.take("some string"); return x; } int main() { X x1 = SomeFunction1(); std::cout << "\n " << x1.say() << "\n"; X x2 = SomeFunction2(); std::cout << "\n " << x2.say() << "\n"; x2 = SomeFunction2(); std::cout << "\n " << x2.say() << "\n\n"; }