// MT4Q2 #include #include // if you use reference counting, then you must create on heap class Message { public: Message(const std::string& msg) : msg_(msg), refCount(0) {} ~Message() { std::cout << "\n destroying Message: " << this->toString(); } operator std::string& () { return msg_; } static Message* makeHeapMessage(const Message& msg) { Message* pMsg = new Message(msg); return pMsg->AddRef(); } Message* AddRef() { ++refCount; return this; } Message* Release() { if(--refCount == 0) delete this; return this; } std::string toString() { return msg_; } private: std::string msg_; long refCount; }; std::ostream& operator<<(std::ostream& out, Message& msg) { std::string temp = msg; out << temp.c_str(); return out; } std::istream& operator>>(std::istream& in, Message& msg) { static_cast(msg).clear(); std::string& temp = msg; char ch; while(true) { in.get(ch); if(ch == '\n' || ch == '\r' || !in.good()) break; temp += ch; } return in; } void main() { Message msg = "msg #1"; std::cout << "\n " << msg; std::cout << "\n Please enter message string: "; std::cin >> msg; std::cout << " " << msg; Message* pMsg1 = Message::makeHeapMessage(Message("a msg")); Message* pMsg2 = pMsg1->AddRef(); std::cout << "\n " << *pMsg1 << ", " << *pMsg2; std::cout.flush(); pMsg2->Release(); pMsg1->Release(); std::cout << "\n\n Now leaving main\n\n"; }