当构造函数引发异常并使用自定义new时,C ++如何释放内存 [英] How does C++ free the memory when a constructor throws an exception and a custom new is used
问题描述
我看到以下结构:
-
如果
-
new X
将释放内存.
X
构造函数抛出异常,则new X
will free the memory ifX
constructor throws.
operator new()
可以重载.
运算符新的重载的规范定义是void *operator new(size_t c, heap h)
和相应的operator delete
.
The canonical definition of an operator new overload is void *operator new(size_t c, heap h)
and the corresponding operator delete
.
最常见的运算符new重载是new放置,即void *operator new(void *p) { return p; }
The most common operator new overload is placement new, which is void *operator new(void *p) { return p; }
几乎总是不能在放置位置new
的指针上调用delete
.
You almost always cannot call delete
on the pointer given to placement new
.
这导致一个问题:当X
构造函数抛出并使用重载的new
时,如何清理内存?
This leads to a single question: How is memory cleaned up when X
constructor throws and an overloaded new
is used?
推荐答案
当构造函数引发异常时,将调用匹配的delete.不会为抛出的类调用析构函数,但是已成功调用其构造函数的该类的任何组件都将调用其析构函数.
When a constructor throws an exception the matching delete is called. The destructor is not called for the class that threw but any components of the class that have successfully had their constructors called will have their destructors called.
这篇关于当构造函数引发异常并使用自定义new时,C ++如何释放内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!