TheRiver | blog

You have reached the world's edge, none but devils play past here

0%

rule of three-five-zero

参考

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; // raw pointer used as a handle to a dynamically-allocated memory block

void init(const char* s)
{
std::size_t n = std::strlen(s) + 1;
cstring = new char[n];
std::memcpy(cstring, s, n); // populate
}
public:
rule_of_three(const char* s = "") { init(s); }

~rule_of_three()
{
delete[] cstring; // deallocate
}

rule_of_three(const rule_of_three& other) // copy constructor
{
init(other.cstring);
}

rule_of_three& operator=(const rule_of_three& other) // copy assignment
{
if(this != &other) {
delete[] cstring; // deallocate
init(other.cstring);
}
return *this;
}
};

析构函数,拷贝构造函数,赋值拷贝运算符函数,如果用户实现了其中一个,则应该实现所有的三个。主要针对类内成员作为指针指向对象或者是句柄,而导致的释放关闭问题。

  • 如果只实现了析构函数,系统默认拷贝构造函数是浅拷贝,后面涉及多次析构同一地址
  • 如果只实现了拷贝构造函数,析构

ending

82483600_p0_master1200.jpg

----------- ending -----------