假设我们有以下C ++代码:
struct A
{
int* a;
A()
{
a = new int(5);
}
~A()
{
delete a;
}
};
struct B
{
A a;
int b;
B()
{
a = A();
b = 10;
}
};
int main()
{
B b;
return 0;
}
运行它时,A的析构函数会被调用两次,但为什么呢? 根据我的理解,B的隐式析构函数调用B成员的所有析构函数,这很好,但是第二次调用A的析构函数何时发生?为什么?在这种情况下处理内存的正确方法是什么?
答案 0 :(得分:0)
数据成员的构造函数在类的构造函数中调用。除非使用初始化列表显式指定构造函数,否则在执行到达构造函数中的第一行之前,将调用每个成员的默认构造函数,在这种情况下,将调用该构造函数。 请调试这个,你会了解更多,甚至手动没有debuger
#include <iostream>
#include <stdlib.h>
struct A
{
int* a;
A()
{
a = new int(5);
std::cout<<"A()"<<std::endl;
}
~A()
{
std::cout<<"~A()"<<std::endl;
delete a;
}
};
struct B
{
A a; // if you remove this & you remove line 26 there wont be any call to A()
int b;
B()
{
// a = A(); // even if this line is removed there still a call to A() constructor
b = 10;
}
};
void pause() // a simple pause function , that we let the system call before exiting to see the output
{
system("pause");
}
int main()
{
atexit(pause); // to pause after calling all destructors
B * b = new B();
delete b;
B * b1 = new B();
delete b1;
return 0;
}