0%

C++踩坑记录:构造与析构函数

我是练习时长一年的 C++ 个人练习生,喜欢野指针、模板报错和未定义行为(undefined behavior)。之前在写设计模式的『工厂模式』时,一脚踩到了构造、继承和 new 组合起来的坑,现在也有时间来整理一下了。

构造函数

众所周知:在创建对象时,防止有些成员没有被初始化导致不必要的错误,在创建对象的时候自动调用构造函数(无声明类型),完成成员的初始化。即:

1
2
3
4
Class c // 隐式,默认构造函数
Class c = Class() // 显示,默认构造函数
Class c = Class("name") // 显示,非默认构造函数
Class* c = new Class // 隐式,默认构造函数
  • 构造函数执行前,对象不存在
  • 构造函数创建对象后,对象不能调用构造函数
  • 类中如果不定义构造函数,编译器提供有默认的构造函数,无参数,也不执行任何额外的语句
  • 如果提供非默认构造函数,没有默认构造函数将会出错。所以要定义一个不接受任何参数的构造函数,并为成员定义合理的值
  • 一般而言,默认的构造函数是用来对所有类成员做隐式初始化的
  • 自己定义的构造函数一般用使用列表初始化来初始化参数
  • 通过构造函数对成员赋值,要优于通过函数为成员赋值
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
#include <iostream>
using namespace std;

class Stone {
private:
int weight{0};
double radius{0.0};
public:
Stone() {
cout << "Class Stone was created by default creator" << endl;
};
Stone(int w, double r) : weight{w}, radius{r} {
cout << "Class Stone was created by custom creator" << endl;
}
void showInfo() {
cout << "Weight: " << this->weight << ", Radius: "
<< this->radius << endl;
}
};

int main (){
// 隐式,成员有默认值
Stone s1;
s1.showInfo();
// 显式,通过列表初始化,为成员赋值
Stone s2 = Stone(12, 3.3);
s2.showInfo();
return 0;
}

通过构造函数实现的类型转换

观察以下的代码,我们发现 Stone s2;s2 = 3.3; 这样将一个 double 类型的数据赋值给类类型并没有出错,这是隐式类型转换,从参数类型到类类型。

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
#include <iostream>
using namespace std;

class Stone {
private:
int weight{0};
double radius{0.0};
public:
Stone() {
cout << this << endl;
cout << "Class Stone was created by default creator" << endl;
};
Stone(double r) : radius{r} {
cout << this << endl;
cout << "Class Stone was created by parameter radius" << endl;
}
Stone(int w) : weight{w} {
cout << this << endl;
cout << "Class Stone was created by parameter weight" << endl;
}
void showInfo() {
cout << "Weight: " << this->weight << ", Radius: "
<< this->radius << endl;
}
};

int main (){
Stone s2 = 3.3; // Class Stone was created by parameter radius
s2.showInfo();
return 0;
}

这是因为:接受一个参数的构造函数允许使用赋值语法来为对象赋值。s2=3.3 会创建 Stock(double) 临时对象,临时对象初始化后,逐成员赋值的方式复制到对象中,在几个构造函数中加入了 cout << this 的语句,由对象的地址不同,可以判断该赋值语句额外生成了临时对象。

为了防止隐式转换带来的危险,可以使用关键字 explicit 关闭这一特性,这样就得显式完成参数类型到类类型的转换:s = Stock(1.3);不过,得保证没有二义性。

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
33
#include <iostream>
using namespace std;

class Stone {
private:
int weight{0};
double radius{0.0};
public:
Stone() {
cout << this << endl;
cout << "Class Stone was created by default creator" << endl;
};
// 都关闭
explicit Stone(double r) : radius{r} {
cout << this << endl;
cout << "Class Stone was created by parameter radius" << endl;
}
explicit Stone(int w) : weight{w} {
cout << this << endl;
cout << "Class Stone was created by parameter weight" << endl;
}
void showInfo() {
cout << "Weight: " << this->weight << ", Radius: "
<< this->radius << endl;
}
};

int main (){
// Stone s2 = 1; // 错误
Stone s2{1}; // 正确
s2.showInfo();
return 0;
}

上述代码中,如果 Stone(int w) 没有被关闭,那么 s2=3.3 将调用这一构造函数。所以构造函数建议都加上 explicit 声明。

explicit 关键字与构造函数

前文提到过,如果构造函数加上了这个 explicit 限制,那么一些隐式的调用将不被允许,以函数返回为例:

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>

class A{
public:
int* arr;
int b;
A() = default;
A(int c) {
std::cout << "para constructor was called" << std::endl;
arr = new int[c];
b = c;
for (int i = 0; i < b; i++)
arr[i] = i;
}
explicit A(A const& B) {
std::cout << "copy constructor was called" << std::endl;
this->b = B.b;
this->arr = new int[b];
for (int i = 0; i < b; i++) {
this->arr[i] = B.arr[i];
}
}
explicit A(A&& B) {
std::cout << "move constructor was called" << std::endl;
this->b = B.b;
this->arr = B.arr;
B.arr = nullptr;
}
void show_addr() {
std::cout << this << std::endl;
}
};

// 这个函数错误
// A create_data() {
// A a(10);
// a.show_addr();
// return a;
// }

int main () {
A a(10); // para constructor,复制消除,只调用一次构造函数
a.show_addr();
A b{a}; // copy constructor
A c{std::move(a)}; // copy constructor
b.show_addr();
c.show_addr();
// std::cout << a.arr[2] << std::endl;
return 0;
}

如上的程序中有很多的细节:

  1. 构造函数使用了成员初始化列表。减少一次构造函数;常量成员,引用类型等,因为常量只能初始化,引用必须定义的时候初始化,所以必须放在初始化列表里面。
  2. 将拷贝构造函数和移动构造函数声明为 explicit,导致 create_data 函数出错,这是因为:返回局部变量要进行 move/copy,就算有复制消除也要保证构造函数可见,因为局部变量东西都在函数的栈上,外面要接的话就要复制/移动出去。因此不建议对构造函数增加 explicit 关键字。
  3. 复制消除:在满足以下任一条件时,编译器将省略类对象的复制和移动构造,导致零复制的按值传递语义:
    1. 在 return 语句中,当操作数是一个与函数返回类型相同的类类型的纯右值时
    2. 在对象的初始化中,当初始化器表达式是一个与变量类型相同的类类型的纯右值时

也就是,A a = A() 这种理论上需要两次构造函数的语句,只需要执行一次构造函数。

派生类的构造函数

派生类要注意的是:派生类被构造之前,通过调用一个基类的构造函数,创建基类完成基类数据成员的初始化;也就是说,基类对象在程序进入派生类构造函数之前被创建。那么,可以通过初始化列表传递给基类参数,不传递的话,调用基类的默认的构造函数,如下述程序中的:Gem(){}:Stone()

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
33
34
35
36
37
38
39
40
41
42
#include <iostream>
using namespace std;

class Stone {
private:
int weight{0};
double radius{0.0};
public:
Stone() {
cout << "This object was in address: " << this << endl;
};
Stone(int w, double r) : weight{2}, radius{r} {};
void showInfo() {
cout << "Weight: " << this->weight << ", Radius: " << this->radius;
}
int getWeight(){
return this->weight;
}
auto getRadius() -> double {
return this->radius;
}
};

class Gem : public Stone {
private:
double price;
public:
Gem(){};
Gem(double p, int w, double r) : Stone(w, r), price{p} {};
void show() {
cout << "Weight: " << this->getWeight() << ", Radius"
<< this->getRadius();
}
};

int main (){
Gem g1; // call default
Gem g2 = Gem(1300, 1, 2.3); // call custom
// g.setWeight(130);
g2.show();
return 0;
}
  • 首先创建基类对象
  • 派生类通过初始化列表(只能用在构造函数)将基类信息传递给基类的构造函数
  • 派生类构造函数可以为派生类初始化新的成员

析构函数

对象过期时,程序会调用对象的析构函数完成一些清理工作,如释放变量开辟的空间等。如构造函数使用了 new 来申请空间,析构就需要 delete 来释放空间。如果没有特别声明析构函数,编译器会为类提供默认的析构函数,在对象作用域到期、被删除时自动被调用。

stock1 = Stock(),这种就申请了一个临时变量,变量消失时会调用析构函数。此外,这种局部变量放在栈区,先入后出,也就是,最后被申请的变量最先被释放。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

class Stone {
private:
int weight{0};
double radius{0.0};
public:
Stone() {
cout << "This object was in address: " << this << endl;
};
~Stone() {
cout << this << " Object was deleted." << endl;
}
};

int main (){
{
Stone s1;
Stone s2;
}
return 0;
}

继承中的析构函数

继承类比较容易理解,毕竟都学过面向对象。公有继承的时候,基类的公有成员也是派生类的共有成员;私有成员也是派生类的一部分,不过需要共有或保护方法来访问。但是但是但是,派生类和基类的析构函数之间,也是一个坑。在继承中:

  • 如果一个方法不是虚方法,那么将根据引用类型或指针类型选择执行的方法
  • 如果一个方法是虚方法,将根据指针或引用指向对象的类型选择执行的方法

在继承中,对象的销毁顺序和创建相反。创建时先创建基类,而后创建子类;销毁时,先调用子类的析构函数,而后自动调用基类的析构函数。因此,对于基类而言,建议将析构函数写成虚方法。如果析构不是虚方法,对于以下情况,只有基类的析构被调用;如果析构是虚方法,子类、基类的析构方法都被调用。可以尝试删除下述代码的 virtual 来观察结果:

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
using namespace std;

class Stone {
private:
int weight{0};
double radius{0.0};
public:
Stone() {
cout << "This object was in address: " << this << endl;
};
Stone(int w, double r) : weight{2}, radius{r} {};
void showInfo() {
cout << "Weight: " << this->weight << ", Radius: "
<< this->radius;
}
int getWeight(){
return this->weight;
}
auto getRadius() -> double {
return this->radius;
}
virtual ~Stone() {
cout << "Stone class was deleted." << endl;
}
};

class Gem : public Stone {
private:
double price;
public:
Gem() {};
Gem(double p, int w, double r) : Stone(w, r), price{p} {};
void show() {
cout << "Weight: " << this->getWeight() << ", Radius"
<< this->getRadius();
}
~Gem() {
cout << "Gem class was deleted." << endl;
}
};

int main (){
Stone* s1 = new Gem(2.3, 2, 3.2);
delete s1;
// Gem* g1 = new Gem(2.3, 2, 1.2);
// delete g1;
return 0;
}

应用

大概常见的坑在上面都记录好了,来看一段我写的危险的程序(我大概抽象了一下),覆盖了:野指针和为定义行为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;

class A {
private:
int* a;
public:
int* create() {
a = new int();
return a;
}
~A(){
delete a;
}
};

int main () {
A a;
int* b = a.create();
delete b;
return 0;
}
  1. 每次调用 create 都会 new 一次,但只 delete 了一次。
  2. 如果没有调用 create 直接析构,未定义行为
  3. 如果 b 持有了 a.create() 的指针,然后 a 提前析构,那么 b 是野指针
  4. delete b 是没必要的。这样会 double free,也是未定义行为
  5. 上述代码没有区分类里面 new 且 返回的东西要在哪删除合适
  6. 可以让类来管理这一个 new,修改一下 create 的实现或者干脆在构造 new,在析构 delete
感谢上学期间打赏我的朋友们。赛博乞讨:我,秦始皇,打钱。

欢迎订阅我的文章