gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 06:50:15 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com