当前位置:
首页 >
Effective C++ 学习笔记(11)
发布时间:2023/12/9
63
豆豆
生活随笔
收集整理的这篇文章主要介绍了
Effective C++ 学习笔记(11)
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
确定基类有虚析构函数
{
public:
A()
{
cout<<"A constructor"<<endl;
}
~A()
{
cout<<"A destructor"<<endl;
}
};
class B: public A
{
public:
B()
{
cout<<"B constructor"<<endl;
}
~B()
{
cout<<"B destructor"<<endl;
}
};
int main()
{
A * p =new B();
delete p;
return 0;
}
执行结果:
对此解释:C++语言标准规定,当通过基类指针删除派生类的对象,而基类又没有虚析构函数,结果是不确定的。
对此,将A的析构函数改为虚函数:
class A{
public:
A()
{
cout<<"A constructor"<<endl;
}
virtual ~A()
{
cout<<"A destructor"<<endl;
}
};
执行结果:
结果正确。
以上我们是在堆上分配的内存。
改写main函数,在栈上分配:
int main(){
B b;
return 0;
}
结果同上。分配在栈上的对象自动调用构造函数与析构函数。
转载于:https://www.cnblogs.com/DanielZheng/archive/2011/08/03/2126218.html
总结
以上是生活随笔为你收集整理的Effective C++ 学习笔记(11)的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: Winform开发中另一种样式的OutL
- 下一篇: effective C++ 条款 3:尽