C++程序出错如何删除动态分配的对象?

How a dynamically allocated object is deleted if an error occur in the program in C++?

我想知道如果程序中发生错误,如何删除动态分配的对象。想象一下:

int main() {
  int *ptr = new int();

  int result = 15 / 0;

  delete ptr;
}

除以0是完全不可能的,所以与ptr关联的int永远不会被删除?

您应该使用允许释放的“智能指针”,即使在您调用之前抛出异常也是如此。

unique_ptr<int> ptr(new int());

智能指针包含原始指针,允许删除他。

这是文档: https://docs.microsoft.com/fr-fr/cpp/cpp/smart-pointers-modern-cpp?view=vs-2019

How a dynamically allocated object is deleted if an error occur in the program in C++?

没有删除。

而且因为指针值会丢失,所以永远无法删除。这称为内存泄漏。

Division by 0 is completely impossible, so the int associated to the ptr will never be deleted?

请注意,除以零的行为是未定义的。因此不能保证一定会出错。


如果一个程序异常终止,那么就会有一些内存没有被释放。这个泄漏很好,因为程序正在终止。操作系统将回收为该进程保留的所有内存。

比较有问题的情况是异常,可能会被捕获,程序可能会继续执行。对于异常安全的程序,您不得在持有拥有的裸指针时执行可能抛出的操作。事实上,您应该尽可能避免拥有裸指针。相反,请使用 RAII 容器和智能指针。