gpt4 book ai didi

c++ - 从重载运算符删除中调用成员函数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:26:49 27 4
gpt4 key购买 nike

这篇文章 Binary-compatible C++ Interfaces包含代码:

class Window {
public:
// ...
virtual void destroy() = 0;

void operator delete(void* p) {
if (p) {
Window* w = static_cast<Window*>(p);
w->destroy(); // VERY BAD IDEA
}
}
};

对我来说,这似乎是错误的:operator delete()原始内存 上工作,目的是释放它。该对象的析构函数已被调用,因此调用 destroy() 对“幻影”对象有效(如果它有效的话)。确实:这就是为什么 operator delete() 采用 void* 而不是 Window*(在本例中)。

所以,设计有缺陷,对吧? (如果是正确的,为什么是正确的?)

最佳答案

我同意(假设 Window::destroy 不是静态成员函数):

3.8p1: The lifetime of an object of type T ends when: if T is a class type with a non-trivial destructor, the destructor call starts, or [...]

3.8p5: [...] After the lifetime of an object has ended and before the storage which the object occupied is reused or released, any pointer that refers to the storage location where the object [...] was located may be used but only in limited ways. ... If the object will be or was of a non-POD class type, the program has undefined behavior if: the pointer is used to access a non-static data member or call a non-static member function of the object, or [...]

(强调我的)

关于c++ - 从重载运算符删除中调用成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5437550/

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