delete两次内存为什么程序还能运行?
请教高手!
下面代码的运行结果:
A constructor invoked.
A deconstructor invoked.
A deconstructor invoked.
因为两个shared_ptr在指针pa上执行了两次delete,调用了两次析构函数。
但是第二次delete的时候应该是在delete已经释放的内存了,程序并没有报错?
请问这是为什么呢?
#include <iostream>
#include <memory>
class A
{
public:
A(int i) : m_i(i)
{
std::cout << "A constructor invoked." << std::endl;
}
~A()
{
std::cout << "A deconstructor invoked." << std::endl;
}
private:
int m_i = 0;
};
void doubleDelete()
{
A* pa = new A(30);
std::shared_ptr<A> spa1(pa);
std::shared_ptr<A> spa2(pa);
}
int main()
{
doubleDelete();
return 0;
}