gpt4 book ai didi

c++ - 在基类中重载运算符 delete

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:32:38 25 4
gpt4 key购买 nike

来自 C++ 标准 (ISO/IEC 14882:2003(E)),§12.5.4,关于重载 operator delete:

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 found by the lookup in the definition of the dynamic type's virtual destructor (12.4). 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.

§12.5.7 也很有趣:

Since member allocation and deallocation functions are static they cannot be virtual. [Note: however, when the cast-expression of a delete-expression refers to an object of class type, because the deallocation function actually called is looked up in the scope of the class that is the dynamic type of the object, if the destructor is virtual, the effect is the same. For example,

struct B {
virtual ˜B();
void operator delete(void*, size_t);
};
struct D : B {
void operator delete(void*);
};
void f()
{
B* bp = new D;
delete bp; // uses D::operator delete(void*)
}

Here, storage for the non-array object of class D is deallocated by D::operator delete(), due to the virtual destructor.]

看完之后,我想知道...

  • 标准的这一部分是否得到所有主要 C++ 编译器(MSVC++、GCC)的完全支持?
  • 如果是这样,他们是怎么做到的?隐藏虚函数? “特殊”虚拟析构函数调用? RTTI?
  • 使用标准中的示例:如果 f() 和 D::operator delete() 在单独的 EXE/DLL/DSO 中定义,是否会出现问题? (当然,假设一切都是使用相同的编译器编译的)

§5.3.5.5 也可能相关:

In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand's dynamic type and the static type shall have a virtual destructor or the behavior is undefined. In the second alternative (delete array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined.

最佳答案

我不太了解 VC++ ABI,但 Itanium ABI 有详细的文档。

抬头看the name mangling scheme ,一见:

<ctor-dtor-name> ::= C1     # complete object constructor
::= C2 # base object constructor
::= C3 # complete object allocating constructor
::= D0 # deleting destructor
::= D1 # complete object destructor
::= D2 # base object destructor

有趣的是:D0 # deleting destructor,这意味着即使delete是非虚的,因为它是从虚析构函数中调用的,所以它可以被认为是虚的所有效果和目的。

关于c++ - 在基类中重载运算符 delete,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6355438/

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