当基没有删除基指针的虚拟析构函数厌恶效果时,为空子类

Empty subclass when base has no virtual destructor - averse effects of delete base pointer?

本文关键字:子类 析构函数 删除 指针 虚拟      更新时间:2023-10-16

根据这个问题,我想知道:

class MyVector : public std::vector<int> {};
std::vector<int>* obj = new MyVector;
delete obj;

这有什么不利的影响吗?

根据标准,您调用的是Undefined Behavior,所以任何事情都可能发生。但我想,在大多数正常的实现中,MyVector的析构函数实际上是一个无操作(当然,除了调用std::vector的析构因子),所以在实践中是安全的。

另一个问题是,为什么首先要动态地分配一个向量(类)。我认为这是一个相当不寻常的情况。如果你真的需要动态分配,你可以考虑在std::shared_ptr中强制拥有所有权(或者推出你自己的带有类型擦除删除器的智能指针),它能够在构建时修复正确的析构函数(感谢@CantChooseUsernames的建议)。

即使类为空。。它仍然分配一些东西(至少1个字节)。。

https://ideone.com/CpNlNG

#include <iostream>
#include <vector>

void* operator new(std::size_t count)
{
    std::cout<<"Allocated: "<<count<<" bytesn";
    return malloc(count);
}
class MyVector : public std::vector<int> {};
class Empty {};
int main()
{
    std::vector<int>* obj = new MyVector;
    delete obj;
    Empty* empty = new Empty;
    delete empty;
    return 0;
}

结果:

Allocated: 12 bytes
Allocated: 1 bytes

即使在O3打开的情况下也是如此。如果你不使用空类,它当然会得到优化。