///////////////////////////////////////////////////////////////////// // MT3Q8.cpp #include ////////////////////////////////////////// // class that shares its reference // could have state lifetime problems class B1 { public: B1(std::string& str) : s(str) {} B1(const B1& b); B1& operator=(const B1& b); void say() { std::cout << "\n " << s.c_str(); } private: std::string& s; }; B1::B1(const B1& b) : s(b.s) {} B1& B1::operator =(const B1 &b) { // does nothing, since the reference is shared return *this; } //////////////////////////////////////////// // class that shares a pointer to string // also could have lifetime problems class B2 { public: B2(std::string& str) : pS(&str) {} B2(const B2& b); B2& operator=(const B2& b); void say() { std::cout << "\n " << pS->c_str(); } private: std::string* pS; }; B2::B2(const B2& b) : pS(b.pS) {} B2& B2::operator=(const B2& b) { if(this == &b) return *this; if(pS != b.pS) { // delete pS; do this if you know pS points to heap pS = b.pS; } return *this; } void main() { std::string str = "I'm a B1 object"; B1 b1a(str); b1a.say(); B1 b1b = b1a; b1b.say(); std::cout << "\n\n"; B1 b1c(str); b1c.say(); b1c = b1a; b1c.say(); std::cout << "\n\n"; str = "I'm a B2 object"; B2 b2a(str); b2a.say(); B2 b2b = b2a; b2b.say(); std::cout << "\n\n"; std::string str2 = "I will be assigned"; B2 b2c(str2); b2c.say(); b2c = b2a; b2c.say(); std::cout << "\n\n"; }