当基没有删除基指针的虚拟析构函数厌恶效果时,为空子类
Empty subclass when base has no virtual destructor - averse effects of delete base pointer?
根据这个问题,我想知道:
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打开的情况下也是如此。如果你不使用空类,它当然会得到优化。
相关文章:
- 优先顺序:智能指针和类析构函数
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何正确定义C++类析构函数并将其链接到主文件?
- 继承的类析构函数
- C++类析构函数使用新值而不是实际值
- 单例类析构函数无法清理 (SDL_Quit) MinGW
- C++类析构函数删除成员(如果"owner"?
- 如何从类成员函数返回指针,例如 size_t * class :: function(); 并使用类析构函数 ~size
- 抽象类析构函数与继承"Shutdown"函数
- C++11:我可以显式调用基类析构函数来销毁派生类吗
- C++销毁顺序:在类析构函数之前调用字段析构函数
- C++ 由于类析构函数中的指针设置为 NULL 而导致的内存泄漏
- 由类析构函数完成的同步
- 使用线程销毁类析构函数中的shared_ptr成员变量
- C++ 类析构函数删除部分但不是全部成员数据
- 模板化子类析构函数中的隔离错误
- 如何调用所有基类析构函数?(或通用函数)
- 如何使用指针向量实现类析构函数 C++.
- 基类析构函数不是虚拟的,子类析构函数是虚拟的,程序崩溃
- 父类析构函数删除具有外部启动元素的子类