C++栈里的局部对象在函数返回时不总是自动调用其析构函数
感觉特坑!ClxDerived b(); //测试表明没调用析构函数, 也没有调用构造函数!
#include <iostream>
using namespace std;
#include <stdio.h>
class ClxBase
{
public:
ClxBase() { cout << "constructor base Output from the constructor of class base!" << endl; };
virtual ~ClxBase() { cout << "destructor base Output from the destructor of class base!" << endl; };
void DoSomething() { cout << "DoSomething base Do something in class ClxBase!" << endl; };
};
class ClxDerived : public ClxBase
{
int i;
public:
ClxDerived(int j) { cout << "constructor derived(with para) Output from the constructor of class base!" << endl; i = j;};
ClxDerived( ) { cout << "constructor derived(void) Output from the constructor of class base!" << endl; i = 999999999;};
~ClxDerived() { cout << "destructor derived Output from the destructor of class ClxDerived!i = " << i << endl;};
void DoSomething() { cout << "DoSomethingderived Do something in class ClxDerived! i = " << i << endl; };
};
// 代码
int abc ()
{
ClxDerived a(2);
//ClxDerived b
ClxDerived b(); //测试表明没调用析构函数, 也没有调用构造函数!
ClxDerived c;
ClxBase *pTest = new ClxDerived(3);
pTest->DoSomething();
//delete pTest;
return 0;
}
int main ()
{
abc ();
printf ("heheh\r\n");
}
# g++ t.c -o t
# ./t
constructor base Output from the constructor of class base!
constructor derived(with para) Output from the constructor of class base!
constructor base Output from the constructor of class base!
constructor derived(void) Output from the constructor of class base!
constructor base Output from the constructor of class base!
constructor derived(with para) Output from the constructor of class base!
DoSomething base Do something in class ClxBase!
destructor derived Output from the destructor of class ClxDerived!i = 999999999
destructor base Output from the destructor of class base!
destructor derived Output from the destructor of class ClxDerived!i = 2
destructor base Output from the destructor of class base!
heheh 因为这不是定义了一个ClxDerived变量b hellioncu 发表于 2016-05-26 09:57 static/image/common/back.gif
因为这不是定义了一个ClxDerived变量b
ClxDerived b(); //测试表明没调用析构函数, 也没有调用构造函数!
那这既然没有构造对象,那到底是干啥了? mordorwww 发表于 2016-05-26 10:11 static/image/common/back.gif
ClxDerived b(); //测试表明没调用析构函数, 也没有调用构造函数!
那这既然没有构造对象,那到底 ...
函数申明 本帖最后由 mordorwww 于 2016-05-27 09:36 编辑
同笑:em30: :em30: :em30: :em30: :em30: :em30: :grin: 同笑:mrgreen::mrgreen::mrgreen::mrgreen: 这是声明了一个函数,老早之前见过这个坑了 现在版本高一点的编译器,好像是有告警或者报错了
页:
[1]