int main()
{
A* x = new B(10, 20);
x->opt1();
delete x;
return 0;
}
int main()
{
B x(10, 20);
return 0;
}
因此,第一個有內存泄漏,我明白,因爲x是一個A對象,指向一個B對象。如果A不是指針,它仍然會有內存泄漏?內存泄漏C++指針
爲什麼第二個函數沒有內存泄漏?我們不需要刪除x?
class A
{
private:
int* a;
public:
A(int size) {
a = new int[size];
}
~A() {
if (a) {
delete [] a;
}
};
virtual void opt1() {
cout << "A::opt1()" << endl;
}
};
class B : public A
{
private:
float* b;
public:
B(int size1, int size2) : A(size1) {
b = new float[size2];
}
~B() {
if(b){
delete [] b;
}
}
virtual void opt1() {
cout << "B::opt1()" << endl;
}
};
確實'A'有虛擬析構函數嗎? –