sof*_*ver 1 c++ virtual virtual-destructor c++11
我试图看到调用属于长层次结构的类的虚拟析构函数的影响:类A到类E.
奇怪的是,析构函数不会向控制台写任何内容.我首先想到也许它正在发生,因为主要也在退出.因此,我将所有测试代码放在一个名为test()的函数中,并从main()中调用,这样当测试返回时,我会看到析构函数的脚印.但是,没有!控制台上没有"cout"标志出现!
#include <iostream>
using namespace std;
//A constructor cannot be virtual but a destructor can.
class A {
public:
A() {
cout << "A constructor" << endl;
}
virtual ~A() {cout << "A destructor" << endl;}
};
class B :public A {
public:
B() {
cout << "B constructor" << endl;
}
virtual ~B() {cout << "B destructor" << endl;}
};
class C :public B {
public:
C() {
cout << "C constructor" << endl;
}
virtual ~C() {cout << "C destructor" << endl;}
};
class D :public C {
public:
D() {
cout << "D constructor" << endl;
}
~D() {cout << "D destructor" << endl;}
};
class E :public D {
public:
E() {
cout << "E constructor" << endl;
}
~E() {cout << "E destructor" << endl;}
};
void test() {
cout << "Test1 begins..." << endl;
A* a1 = new D();
cout << "Test2 begins..." << endl;
A* a2 = new E();
}
int main() {
test();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
嗯......你真的泄漏了那些.
new关键字创建的每个对象必须具有等效性delete:
void test() {
cout << "Test1 begins..." << endl;
A* a1 = new D();
cout << "Test2 begins..." << endl;
A* a2 = new E();
delete a1;
delete a2;
}
Run Code Online (Sandbox Code Playgroud)
开发人员(仅在您的情况下)总是忘记删除动态分配的对象,因此引入了智能指针:
void test() {
cout << "Test1 begins..." << endl;
std::unique_ptr<A> a1(new D());
cout << "Test2 begins..." << endl;
std::unique_ptr<A> a2(new E());
}
Run Code Online (Sandbox Code Playgroud)
无需担心泄漏,因为unique_ptr当它们超出范围时自动删除它们的指针.
| 归档时间: |
|
| 查看次数: |
59 次 |
| 最近记录: |