使用new申请的对象,如果不主动delete掉,在程序运行结束的时候系统释放会调用对象的析构函数呢?我们写个小程序试试
#include <iostream>
#include <string>
class A
{
public:
A(std::string method);
~A();
private:
std::string m_method;
};
A::A(std::string method)
{
m_method = method;
std::cout << "construct A -- " << m_method << std::endl;
}
A::~A()
{
std::cout << "release A -- " << m_method << std::endl;
}
A oa("static");
A* pa = new A("new");
int main()
{
return 0;
}
运行结果
xxx@LP210300018 release % ./release
construct A -- static
construct A -- new
release A -- static
xxx@LP210300018 release %
可以看到,new出来的对象pa,我们没有主动delete pa,那么程序运行结束了系统也不会调用pa的析构函数;而静态全局对象oa的析构函数会被调用。
所以我们在程序开发过程中需要注意,堆上申请的对象,最好不要访问全局对象资源,这样做在程序正常运行中是没问题的,但当程序结束时,全局对象资源会被析构,此时堆对象可能还在运行,会导致非法访问,虽然用户没有没有感知,但会有很多崩溃上报。