- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
考虑以下代码:
class Base {
public:
#ifdef __VIRTUAL__
virtual ~Base() {}
#else
~Base() {}
#endif
};
class Derived : public Base {
public:
~Derived() {}
private:
static void operator delete(void*) = delete;
};
int main() {
Derived d;
}
用cmd编译成功
g++ -std=c++11 main.cpp
但是cmd失败了
g++ -std=c++11 -D__VIRTUAL__ main.cpp
输出显示需要operator delete
main.cpp: In destructor ‘virtual Derived::~Derived()’:
main.cpp:12:17: error: use of deleted function ‘static void Derived::operator delete(void*)’
~Derived() {}
^
main.cpp:14:17: error: declared here
static void operator delete(void*) = delete;
^
main.cpp: In destructor ‘virtual Derived::~Derived()’:
main.cpp:12:17: error: use of deleted function ‘static void Derived::operator delete(void*)’
~Derived() {}
^
main.cpp:14:17: error: declared here
static void operator delete(void*) = delete;
^
这意味着如果我使用虚拟析构函数,我不能删除 operator delete
。
为什么会这样,为什么虚拟析构函数需要全局operator delete
,即使是在栈上创建的。
最佳答案
operator delete
函数仅在删除具有动态存储持续时间的对象时调用。它不是由您的程序调用的。
但是,标准要求如果存在虚拟析构函数,则此函数可用,即使该对象从未实际动态使用也是如此。
在 C++17 标准中,这是 [class.dtor]/13:
At the point of definition of a virtual destructor (including an implicit definition), the non-array deallocation function is determined as if for the expression
delete this
appearing in a non-virtual destructor of the destructor’s class. If the lookup fails or if the deallocation function has a deleted definition, the program is ill-formed. [Note: This assures that a deallocation function corresponding to the dynamic type of an object is available for the delete-expression. —end note ]
为什么标准有此要求?我不知道,但你将不得不找到其他方法来解决你的问题。也许这个线程会有用:Any way to prevent dynamic allocation of a class?
关于c++11 - 为什么虚拟析构函数需要运算符删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56928002/
我是一名优秀的程序员,十分优秀!