问题描述
- C++析构函数是怎么出来的?
-
#include
#include
#include
#includeusing namespace std;
class Door {
public:
void open() const {
cout << "open door horizontally" << endl;
}void close() const {
cout << "close door horizontally" << endl;
}
virtual ~Door()
{
cout << " Door is delete " <<endl;
}
};class DoorController {
protected:
vector _doorVec;public:
void addDoor(Door aDoor) {
_doorVec.push_back(aDoor);
}void openDoor() const {
for_each(_doorVec.begin(), _doorVec.end(), mem_fun_ref(&Door::open));
cout << "openDoor is end" <<endl;
}virtual ~DoorController()
{
cout << "DoorController is delelte" <<endl;
}
};int main()
{
DoorController dc;
Door doorc;
dc.addDoor(doorc);
dc.addDoor(doorc);
// dc.addDoor(Door());
// dc.addDoor(Door());
dc.openDoor();
}
解决方案
析构函数是在程序执行完后自动执行的,释放程序所占用的内存空间,比如申请变量、对象占用的空间等等。。。。
解决方案二:
virtual ~BaseControl(void)
{
if(i_sbHandler)
{
delete i_sbHandler;
i_sbHandler=NULL;
}
}
上面是基类BaseControl的析构函数,写成virtual 防止使用多态的时候,delete 时未执行 该函数
在程序退出的时候
inline static ......<br/><strong>答案就在这里:</strong><a target='_blank' rel='nofollow' href='http://blog.csdn.net/xugangjava/article/details/8477777'>C++ 析构函数</a><br/>
解决方案三:
析构函数用来释放该类所占用的内存空间,如果用户没有定义析构函数,则程序会自动生成一个析构函数