当构造函数引发异常并使用自定义new时,C ++如何释放内存 [英] How does C++ free the memory when a constructor throws an exception and a custom new is used

查看:121
本文介绍了当构造函数引发异常并使用自定义new时,C ++如何释放内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到以下结构:

    如果X构造函数抛出异常,则
  • new X将释放内存.

  • new X will free the memory if X 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆