虚析构
众C++er所周知,在多态发生时,如果父类的虚函数不是虚函数的话,子类指针指向父类对象,在其生命周期结束进行delete时,子类对象只会调用父类的析构函数,子类自己的析构函数无法调用导致内存泄露的风险。 只有声明父类析构为虚函数才能按序正常进行。 下面简单的代码验证:
#include<iostream>
#include<memory>
using namespace std;
class A {
public:
A() {
cout << "is A constract" << endl;
}
~A() {
cout << "is A deconstract" << endl;
}
};
class B :public A {
public:
B() {
cout << "is B constract" << endl;
}
~B() {
cout << "is B deconstract" << endl;
}
};
int main() {
A* pb = new B;
delete pb;
return 0;
}
结果如下: 而声明虚析构以后:
#include<iostream>
#include<memory>
using namespace std;
class A {
public:
A() {
cout << "is A constract" << endl;
}
virtual ~A() {
cout << "is A deconstract" << endl;
}
};
class B :public A {
public:
B() {
cout << "is B constract" << endl;
}
~B() {
cout << "is B deconstract" << endl;
}
};
int main() {
A* pb = new B;
delete pb;
return 0;
}
结果如下:
智能指针
偶然想到的问题:如果用智能指针来管理指向父类的子类指针,如果不用虚析构的话会发生什么? 验证一下:
#include<iostream>
#include<memory>
using namespace std;
class A {
public:
A() {
cout << "is A constract" << endl;
}
~A() {
cout << "is A deconstract" << endl;
}
virtual void func() {
cout << "is A func" << endl;
}
};
class B :public A {
public:
B() {
cout << "is B constract" << endl;
}
~B() {
cout << "is B deconstract" << endl;
}
void func() {
cout << "is B func" << endl;
}
};
int main() {
A* pb = new B;
delete pb;
cout << endl;
shared_ptr<A> pc(new B);
pc->func();
return 0;
}
结果如下:
可以看到,上面那部分是有问题的,而通过智能指针来管理即使不用虚析构也可以正常调用子类的析构函数。
注意智能指针与普通指针的转换问题
#include<iostream>
#include<memory>
using namespace std;
class A {
public:
A() {
cout << "is A constract" << endl;
}
~A() {
cout << "is A deconstract" << endl;
}
virtual void func() {
cout << "is A func" << endl;
}
};
class B :public A {
public:
B() {
cout << "is B constract" << endl;
}
~B() {
cout << "is B deconstract" << endl;
}
void func() {
cout << "is B func" << endl;
}
};
int main() {
A* pb = new B;
delete pb;
cout << endl;
A* pca = new B;
shared_ptr<A> pc(pca);
pc->func();
return 0;
}
这样的智能指针用法其实是通过普通指针强转为一个智能指针对象,这样还是会出现不能正确调用虚函数的问题。 因此:智能指针务必不要用已经存在定义的普通指针进行隐式转换。
|