c++ - 在 operator new 和 "nested"初始化的情况下,实现应该做什么

标签 c++

我知道如果对象的构造函数在这种情况下抛出异常,实现应该释放所有分配的内存:

new T(); // Suppose that T() throws an exception

但是下面的代码呢?

new T(f()); // Suppose that T() does NOT throw any exception, but f() does

在这种情况下,实现应该做什么?那么它应该释放任何分配的内存吗?

最佳答案

在当前的C++标准(C++14,以及之前的C++11和C++03版本)中,未指定内存分配在f()之前还是之后。被评估,但在任何情况下,如果内存已分配,内存将被释放; [expr.new]:

20 - If any part of the object initialization described above79 terminates by throwing an exception, storage has been obtained for the object, and a suitable deallocation function can be found, the deallocation function is called to free the memory [...]

79) This may include evaluating a new-initializer and/or calling a constructor.

这里的 new-initializerf() , 所以如果评估 f()抛出异常,将调用释放函数(如果找到)。

自 C++17 起,内存分配顺序 f() 的求值之前。 ,因此内存将始终被释放:

21 - If any part of the object initialization described above79 terminates by throwing an exception and a suitable deallocation function can be found, the deallocation function is called [...]

请注意,由于内存分配是可省略的,如果实现可以预测将抛出异常,则实际上可以自由地省略分配。

关于c++ - 在 operator new 和 "nested"初始化的情况下,实现应该做什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39330251/

相关文章:

c++ - 转换 unique_ptr 的类型安全吗?

c++ - 新算子的异常安全

c++ - unique_ptr资源设置为nullptr后如何释放?

c++ - 通过引用传递太多参数可能效率低下?

c++ - 保持独立结构的内存堆分配器库?

c++ - 调试visual c++程序时,指定的文件无法执行

c++ - 如何限制在 VS 设计器中创建的编辑框中的数字

c++ - 字符串变量的简单错误

c++ - 将 double 值格式化为小数点后一位

c++ - 这个for循环的时间复杂度是多少(和 `n`有关)?