#ifndef MESSAGE_H_ #define MESSAGE_H_ #include using namespace std; class Message { private: int id; string *textptr; static int instance; // identify Message instantiations public: Message() : id(++instance), textptr(nullptr) { cout << "*** Default constructor: " << *this << endl; } Message(string text) : id(++instance), textptr(new string(text)) { cout << "*** Constructor(" << text << "): " << *this << endl; } virtual ~Message() { cout << "*** Destructor: " << *this << endl; delete textptr; } Message(const Message& other) { id = ++instance; // Copy the other's resources. textptr = new string(*other.textptr); cout << "*** Copy constructor(" << other << "): " << *this << endl; } Message(Message&& other) { // Steal the other's resources. id = other.id; textptr = other.textptr; cout << "*** Move constructor(" << other << "): " << *this << endl; // The other's resources are now stolen. other.id = -other.id; other.textptr = nullptr; } Message& operator =(const Message& other) { if (this != &other) { // Copy the other's resources. textptr = new string(*other.textptr); } cout << "*** Copy assignment(" << other << "): " << *this << endl; return *this; } Message& operator =(Message&& other) { if (this != &other) { // Steal the other's resources. id = other.id; textptr = other.textptr; cout << "*** Move assignment(" << other << "): " << *this << endl; // The other's resources are now stolen. other.id = -other.id; other.textptr = nullptr; } return *this; } friend Message operator +(Message& msg1, Message& msg2) { Message sum = Message(*msg1.textptr + " " + *msg2.textptr); cout << "*** Operator + returns: " << sum << endl; return sum; // returns an rvalue } friend Message add(Message& msg1, Message& msg2) { Message sum = Message(*msg1.textptr + " " + *msg2.textptr); cout << "*** Function add returns: " << sum << endl; return sum; // returns an rvalue } friend ostream& operator <<(ostream& outs, const Message& msg) { cout << "[" << msg.id << "]"; if (msg.textptr != nullptr) cout << *msg.textptr; else cout << ""; return outs; } }; #endif /* MESSAGE_H_ */