// This illustrates the danger of self-assignment. That is, when an // object is assigned to itself, you’ve got to be careful in operator=, // or you might destroy your data before you copy it to yourself. // // This lame class stores a C-style string. #include #include // for strdup() (not ANSI, but POSIX) using namespace std; class Str { public: Str(const char *rhs) { assign(rhs); } Str(const Str &rhs) { assign(rhs.data); } Str& operator=(const Str &rhs) { assign(rhs.data); return *this; } ~Str() { delete[] data; } const char *get() const { return data; } private: void assign(const char *newval) { delete[] data; // Deallocate current value data = strdup(newval); // Allocate memory; copy chars } const char *data = nullptr; }; int main() { Str a="♔♕♖♗♘♙", b("♚♛♜♝♞♟"); cout << a.get() << ' ' << b.get() << '\n'; a = b; cout << a.get() << ' ' << b.get() << '\n'; a = a; cout << a.get() << ' ' << b.get() << '\n'; return 0; }