#include <iostream> #include <string> class NoName { public: NoName(): pstring(new std::string), i(0), d(0) { std::cout << "default ctor is called" << std::endl; } NoName(const NoName& other) : pstring(new std::string(*(other.pstring))), i(other.i), d(other.d) { // C++ 默认的copy ctor是 // pstring(other.pstring),这是浅拷贝,是错的 std::cout << "copy ctor is called" << std::endl; } NoName& operator=(const NoName rhs) { std::cout << "operator= is called" << std::endl; pstring = new std::string; *pstring = *(rhs.pstring); i = rhs.i; d = rhs.d; // C++ 默认的operator=是 // pstring = ths.pstring是浅拷贝,是错误的 return *this; } private: std::string *pstring; int i; double d; }; int main() { std::cout << std::endl <<"------test------" << std::endl; std::cout << "NoName x, y:" << std::endl; NoName x, y; std::cout << std::endl; std::cout << "NoName z(x):" << std::endl; NoName z(x); std::cout << std::endl; std::cout << "x = y:" << std::endl; x = y; std::cout << std::endl; return 0; }
为什么x= y这一步即调用了copy ctor又调用了operator=
------test------ NoName x, y: default ctor is called default ctor is called NoName z(x): copy ctor is called x = y: copy ctor is called operator= is called