经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C++ » 查看文章
C++踩坑实战之构造和析构函数
来源:jb51  时间:2021/7/26 14:07:17  对本文有异议

前言

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

构造函数

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

  1. Class c // 隐式,默认构造函数
  2. Class c = Class() // 显示,默认构造函数
  3. Class c = Class("name") // 显示,非默认构造函数
  4. Class* c = new Class // 隐式,默认构造函数
  • 构造函数执行前,对象不存在
  • 构造函数创建对象后,对象不能调用构造函数
  • 类中如果不定义构造函数,编译器提供有默认的构造函数,无参数,也不执行任何额外的语句
  • 如果提供非默认构造函数,没有默认构造函数将会出错。所以要定义一个不接受任何参数的构造函数,并为成员定义合理的值
  • 一般而言,默认的构造函数是用来对所有类成员做隐式初始化的
  • 自己定义的构造函数一般用使用列表初始化来初始化参数
  • 通过构造函数对成员赋值,要优于通过函数为成员赋值
  1. using namespace std;
  2.  
  3. class Stone {
  4. private:
  5. int weight{0};
  6. double radius{0.0};
  7. public:
  8. Stone() {
  9. cout << "Class Stone was created by default creator" << endl;
  10. };
  11. Stone(int w, double r) : weight{w}, radius{r} {
  12. cout << "Class Stone was created by custom creator" << endl;
  13. }
  14. void showInfo() {
  15. cout << "Weight: " << this->weight << ", Radius: "
  16. << this->radius << endl;
  17. }
  18. };
  19.  
  20. int main (){
  21. // 隐式,成员有默认值
  22. Stone s1;
  23. s1.showInfo();
  24. // 显式,通过列表初始化,为成员赋值
  25. Stone s2 = Stone(12, 3.3);
  26. s2.showInfo();
  27. return 0;
  28. }
  29.  

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

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

  1. using namespace std;
  2.  
  3. class Stone {
  4. private:
  5. int weight{0};
  6. double radius{0.0};
  7. public:
  8. Stone() {
  9. cout << this << endl;
  10. cout << "Class Stone was created by default creator" << endl;
  11. };
  12. // 都关闭
  13. Stone(double r) : radius{r} {
  14. cout << this << endl;
  15. cout << "Class Stone was created by parameter radius" << endl;
  16. }
  17. Stone(int w) : weight{w} {
  18. cout << this << endl;
  19. cout << "Class Stone was created by parameter weight" << endl;
  20. }
  21. void showInfo() {
  22. cout << "Weight: " << this->weight << ", Radius: "
  23. << this->radius << endl;
  24. }
  25. };
  26.  
  27. int main (){
  28. Stone s2;
  29. s2 = 3.3;
  30. s2.showInfo();
  31. return 0;
  32. }
  33.  

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

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

  1. using namespace std;
  2.  
  3. class Stone {
  4. private:
  5. int weight{0};
  6. double radius{0.0};
  7. public:
  8. Stone() {
  9. cout << this << endl;
  10. cout << "Class Stone was created by default creator" << endl;
  11. };
  12. // 都关闭
  13. explicit Stone(double r) : radius{r} {
  14. cout << this << endl;
  15. cout << "Class Stone was created by parameter radius" << endl;
  16. }
  17. explicit Stone(int w) : weight{w} {
  18. cout << this << endl;
  19. cout << "Class Stone was created by parameter weight" << endl;
  20. }
  21. void showInfo() {
  22. cout << "Weight: " << this->weight << ", Radius: "
  23. << this->radius << endl;
  24. }
  25. };
  26.  
  27. int main (){
  28. Stone s2;
  29. s2 = Stone(3);
  30. s2.showInfo();
  31. return 0;
  32. }
  33.  

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

派生类的构造函数

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

  1. using namespace std;
  2.  
  3. class Stone {
  4. private:
  5. int weight{0};
  6. double radius{0.0};
  7. public:
  8. Stone() {
  9. cout << "This object was in address: " << this << endl;
  10. };
  11. Stone(int w, double r) : weight{2}, radius{r} {};
  12. void showInfo() {
  13. cout << "Weight: " << this->weight << ", Radius: " << this->radius;
  14. }
  15. int getWeight(){
  16. return this->weight;
  17. }
  18. auto getRadius() -> double {
  19. return this->radius;
  20. }
  21. };
  22.  
  23. class Gem : public Stone {
  24. private:
  25. double price;
  26. public:
  27. Gem(){};
  28. Gem(double p, int w, double r) : Stone(w, r), price{p} {};
  29. void show() {
  30. cout << "Weight: " << this->getWeight() << ", Radius"
  31. << this->getRadius();
  32. }
  33. };
  34.  
  35. int main (){
  36. Gem g1; // call default
  37. Gem g2 = Gem(1300, 1, 2.3); // call custom
  38. // g.setWeight(130);
  39. g2.show();
  40. return 0;
  41. }
  42.  
  • 首先创建基类对象
  • 派生类通过初始化列表(只能用在构造函数)将基类信息传递给基类的构造函数
  • 派生类构造函数可以为派生类初始化新的成员

析构函数

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

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

  1. using namespace std;
  2.  
  3. class Stone {
  4. private:
  5. int weight{0};
  6. double radius{0.0};
  7. public:
  8. Stone() {
  9. cout << "This object was in address: " << this << endl;
  10. };
  11. ~Stone() {
  12. cout << this << " Object was deleted." << endl;
  13. }
  14. };
  15.  
  16. int main (){
  17. {
  18. Stone s1;
  19. Stone s2;
  20. }
  21. return 0;
  22. }
  23.  

继承中的析构函数

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

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

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

  1. using namespace std;
  2.  
  3. class Stone {
  4. private:
  5. int weight{0};
  6. double radius{0.0};
  7. public:
  8. Stone() {
  9. cout << "This object was in address: " << this << endl;
  10. };
  11. Stone(int w, double r) : weight{2}, radius{r} {};
  12. void showInfo() {
  13. cout << "Weight: " << this->weight << ", Radius: "
  14. << this->radius;
  15. }
  16. int getWeight(){
  17. return this->weight;
  18. }
  19. auto getRadius() -> double {
  20. return this->radius;
  21. }
  22. virtual ~Stone() {
  23. cout << "Stone class was deleted." << endl;
  24. }
  25. };
  26.  
  27. class Gem : public Stone {
  28. private:
  29. double price;
  30. public:
  31. Gem() {};
  32. Gem(double p, int w, double r) : Stone(w, r), price{p} {};
  33. void show() {
  34. cout << "Weight: " << this->getWeight() << ", Radius"
  35. << this->getRadius();
  36. }
  37. ~Gem() {
  38. cout << "Gem class was deleted." << endl;
  39. }
  40. };
  41.  
  42. int main (){
  43. Stone* s1 = new Gem(2.3, 2, 3.2);
  44. delete s1;
  45. // Gem* g1 = new Gem(2.3, 2, 1.2);
  46. // delete g1;
  47. return 0;
  48. }
  49.  

应用

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

  1. using namespace std;
  2.  
  3. class A {
  4. private:
  5. int* a;
  6. public:
  7. int* create() {
  8. a = new int();
  9. return a;
  10. }
  11. ~A(){
  12. delete a;
  13. }
  14. };
  15.  
  16. int main () {
  17. A a;
  18. int* b = a.create();
  19. delete b;
  20. return 0;
  21. }
  22.  
  1. 每次调用 create 都会 new 一次,但只 delete 了一次。
  2. 如果没有调用 create 直接析构,未定义行为
  3. 如果 b 持有了 a.create() 的指针,然后 a 提前析构,那么 b 是野指针
  4. delete b 是没必要的。这样会 double free,也是未定义行为
  5. 上述代码没有区分类里面 new 且 返回的东西要在哪删除合适
  6. 可以让类来管理这一个 new,修改一下 create 的实现或者干脆在构造 new,在析构 delete

总结

到此这篇关于C++踩坑实战之构造和析构函数的文章就介绍到这了,更多相关C++构造和析构函数内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号