我知道如果对象的构造函数在这种情况下抛出异常,实现应该释放所有分配的内存:
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-initializer 是 f()
, 所以如果评估 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/