gpt4 book ai didi

c++ - MSVC 的虚方法崩溃

转载 作者:行者123 更新时间:2023-11-30 00:51:31 27 4
gpt4 key购买 nike

我想我在 MSVC 的编译器(MSVC Ultimate 2012 版本 11.0.61030.00 更新 4)中发现了一个错误。

#include "stdafx.h"

class Base
{
public:
Base()
{
}

void print()
{
printf("Base::print()\n");
}
};

class Derived : public Base
{
public:
Derived() : Base()
{
}

virtual void print()
{
printf("Derived::print()\n");
}
};

class DerivedSquared : public Derived
{
public:
DerivedSquared() : Derived()
{
}

void print()
{
printf("DerivedSquared::print()\n");
}
};

int main(int argc, char *argv[])
{
Base *obj1 = new Base();
Base *obj2 = new Derived();
Base *obj3 = new DerivedSquared();

obj1->print();
obj2->print();
obj3->print();

// Memory leaks are ALWAYS nasty :P
delete obj1;

// CRASH!!!
// File: f:\dd\vctools\crt_bld\self_x86\crt\src\dbgdel.cpp
// _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)
delete obj2;
delete obj3;

return 0;
}

该代码的特殊性在于 Base 的 printf() 方法不是虚拟的,而 Derived 的是。GCC 不会发生这种情况(我已经用 codepad 测试过)。我想知道这是否是一个真正的编译器错误,或者我遗漏了一些明显的东西。

想法?

最佳答案

5.3.5/3 In the first alternative (delete object), if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined.

强调我的。崩溃是未定义行为的一种可能表现。 “似乎没有什么不好的事情发生”是另一回事。

关于c++ - MSVC 的虚方法崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21538879/

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