gpt4 book ai didi

C++虚拟运算符删除?

转载 作者:IT老高 更新时间:2023-10-28 22:35:45 24 4
gpt4 key购买 nike

是否可以有一个虚拟删除操作符?我不是在说析构函数,我指的是实际的运算符重载。

减去(在大多数情况下)重载 new 和 delete 是一个很大的坏主意(是的,我已经知道这是异端邪说),我想知道使用虚拟删除运算符会产生什么样的影响。

我正在考虑尝试使用虚拟删除,因为有时我可能有一个重载删除的子类,存储在基类指针中。从技术上讲,我真的没有看到这个案例取得太多成果,除非我有一个不同节点类型的树(如果你问我,这首先是一个潜在的危险想法)。

我只想知道虚拟或非虚拟删除运算符覆盖的潜在优缺点是什么。

最佳答案

您不能将 operator delete 显式声明为 virtual

它是一个静态成员函数,即使您不提供关键字 static

但是 operator delete 已经是虚拟的,因为使用了在最派生类中定义的那个。您可能会选择将其视为由析构函数调用。甚至可能是。 ;-)


C++11 §12.4/12:
“At the point of definition of a virtual destructor (including an implicit definition (12.8)), the non-array deallocation function is looked up in the scope of the destructor’s class (10.2), and, if no declaration is found, the function is looked up in the global scope.”


C++11 §12.5/4:
“If a delete-expression begins with a unary :: operator, the deallocation function’s name is looked up in global scope. Otherwise, if the delete-expression is used to deallocate a class object whose static type has a virtual destructor, the deallocation function is the one selected at the point of definition of the dynamic type’s virtual destructor (12.4).117 Otherwise, if the delete-expression is used to deallocate an object of class T or array thereof, the static and dynamic types of the object shall be identical and the deallocation function’s name is looked up in the scope of T. If this lookup fails to find the name, the name is looked up in the global scope. If the result of the lookup is ambiguous or inaccessible, or if the lookup selects a placement deallocation function, the program is ill-formed.”

关于C++虚拟运算符删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13897394/

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