c++ - 销毁 delete 是否仍然需要可以访问析构函数?

标签 c++ destructor delete-operator c++20

C++20 引入了“销毁运算符删除”的概念,as described below :

delete-expressions does not execute the destructor for *p before placing a call to operator delete


因此,鉴于以下 struct S :
struct S {
    void operator delete(S* p, std::destroying_delete_t);

private:
    ~S();
};
我希望 delete下面不插入对析构函数的调用,而只是调用我们提供的销毁操作符 delete
delete new S;
但是,GCC/Clang/MSVC 的行为有所不同:DEMO
只有 GCC 不尝试访问 ~S() , 其他人仍然需要 ~S()可访问。
哪一个是正确的?

最佳答案

gcc 是正确的:~S()不需要可以访问。
来自 [expr.delete]/6 :

If the value of the operand of the delete-expression is not a null pointer value and the selected deallocation function (see below) is not a destroying operator delete, the delete-expression will invoke the destructor (if any) for the object or the elements of the array being deleted.


只有在不销毁 delete 的情况下才会调用析构函数。事实上,这就是销毁 delete 的全部意义——让类作者控制如何/何时调用析构函数。因此,不要求析构函数是可访问的——调用它不是由语言决定的,而是由用户决定的。

关于c++ - 销毁 delete 是否仍然需要可以访问析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63797383/

相关文章:

c++ - 在 C++ 中,调用 delete 运算符时会发生什么?

c++ - 不确定在哪里删除对象

c++ - 在 C++ 中将实用程序 DLL 拆分为更小的组件

c++ - snd_pcm_hw_params_set_period_size_near 没有返回好的值

c++ - 尝试处理嵌套对象/结构和动态数组时发生内存泄漏或内存错误。可能的 Xcode/malloc 问题

c++ - 为什么C++偏向析构函数异常?

c++ - 静态工厂方法和静态对象内存泄漏

c++ - 我如何使用 boost::thread::id 作为 unordered_map 的键?

c++ - 重载小于不同类型的运算符

python - 为什么 Python 在销毁对象之前销毁类变量?