我定义了一个父类和一个子类:
struct parent
{
int i;
~parent()
{
printf("~parent()\n");
}
};
struct child : public parent
{
char value[1024*1024];
~child()
{
printf("~child()\n");
}
};
int main()
{
for(int i=0; i < 1000; i++)
{
char* child_ptr = new char[sizeof(child)]();
parent* parent_ptr = reinterpret_cast<parent*>(child_ptr);
delete parent_ptr;
}
return 0;
}
以上代码合法吗?我的意思是内存泄漏吗?我用Windows查过,内存似乎没有泄漏。
最佳答案
严格来说这是一种未定义的行为:reinterpret_cast
不是向上转换的正确行为。它有效,因为 child
指针及其 base
部分的表示可能是相同的。但是如果存在虚函数、多重继承或虚继承,或者只是一些罕见的架构,您的代码可能会失败。
记住:reinterpret_cast
几乎总是错误的。
关于c++ - 在 reinterpret_cast-ing 之后通过父指针调用 delete 时内存是否泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37918392/