C++踩坑实战之构造和析构函数

目录前言构造函数通过构造函数实现的类型转换派生类的构造函数析构函数继承中的析构函数应用总结

前言

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

构造函数

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

Class c // 隐式,默认构造函数Class c = Class() // 显示,默认构造函数Class c = Class("name") // 显示,非默认构造函数 Class* c = new Class // 隐式,默认构造函数

构造函数执行前,对象不存在 构造函数创建对象后,对象不能调用构造函数 类中如果不定义构造函数,编译器提供有默认的构造函数,无参数,也不执行任何额外的语句 如果提供非默认构造函数,没有默认构造函数将会出错。所以要定义一个不接受任何参数的构造函数,并为成员定义合理的值 一般而言,默认的构造函数是用来对所有类成员做隐式初始化的 自己定义的构造函数一般用使用列表初始化来初始化参数 通过构造函数对成员赋值,要优于通过函数为成员赋值

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 类型的数据赋值给类类型并没有出错,这是隐式类型转换,从参数类型到类类型。

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;    s2 = 3.3;    s2.showInfo();    return 0;}

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

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

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;    s2 = Stone(3);    s2.showInfo();    return 0;}

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

派生类的构造函数

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

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(),这种就申请了一个临时变量,变量消失时会调用析构函数。此外,这种局部变量放在栈区,先入后出,也就是,最后被申请的变量最先被释放。

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 来观察结果:

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;}

应用

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

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;}
    每次调用 create 都会 new 一次,但只 delete 了一次。 如果没有调用 create 直接析构,未定义行为 如果 b 持有了 a.create() 的指针,然后 a 提前析构,那么 b 是野指针 delete b 是没必要的。这样会 double free,也是未定义行为 上述代码没有区分类里面 new 且 返回的东西要在哪删除合适 可以让类来管理这一个 new,修改一下 create 的实现或者干脆在构造 new,在析构 delete

总结

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

在乎的是看风景的心情,旅行不会因为美丽的风景终止。

C++踩坑实战之构造和析构函数

相关文章:

你感兴趣的文章:

标签云: