参考
The rule of three/five/zero
rule of three
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class rule_of_three { char* cstring; void init(const char* s) { std::size_t n = std::strlen(s) + 1; cstring = new char[n]; std::memcpy(cstring, s, n); } public: rule_of_three(const char* s = "") { init(s); } ~rule_of_three() { delete[] cstring; } rule_of_three(const rule_of_three& other) { init(other.cstring); } rule_of_three& operator=(const rule_of_three& other) { if(this != &other) { delete[] cstring; init(other.cstring); } return *this; } };
|
析构函数,拷贝构造函数,赋值拷贝运算符函数,如果用户实现了其中一个,则应该实现所有的三个。主要针对类内成员作为指针指向对象或者是句柄,而导致的释放关闭问题。
- 如果只实现了析构函数,系统默认拷贝构造函数是浅拷贝,后面涉及多次析构同一地址
- 如果只实现了拷贝构造函数,析构
ending