问题描述
假设
班级基础
{
公开:
虚拟〜测试() {...}
// ...
};
class派生:公共基地
{
public:
virtual~Endived(){...}
// ...
};
int main()
{
Base * base_ptr = new Derived [10]();
delete [] base_ptr;
返回EXIT_SUCCESS;
}
如果是基类dtor不是虚拟的,''删除[] base_ptr''有
未定义的行为。
将''删除[] base_ptr''调用每个Derived类dtor因为
Base :: ~Base()是虚拟的吗?以上代码中的删除是否有效?。
或者这是否也会调用未定义的行为?
请澄清。
谢谢
V.Subramanian
Suppose
class Base
{
public:
virtual ~Test() { ... }
// ...
};
class Derived : public Base
{
public:
virtual ~Derived() { ... }
// ...
};
int main()
{
Base* base_ptr = new Derived[10]();
delete [] base_ptr;
return EXIT_SUCCESS;
}
If the Base class dtor is not not virtual, ''delete [] base_ptr'' has
undefined behaviour.
Will ''delete [] base_ptr'' call each Derived class dtor because the
Base::~Base() is virtual ? Is the deletion in the above code valid ?.
Or does this also invoke undefined behaviour ?
Kindly clarify.
Thanks
V.Subramanian
推荐答案
不,我们不能这么认为。这不是一个有效的C ++类定义。
----- BEGIN PGP SIGNATURE -----
版本:GnuPG v1.4.7(GNU / Linux)
iD8DBQBIFprDx9p3GYHlUOIRAoPKAJ4wfi5RLzo / ysrMPMMYrWm49EVAEQCffZbw
HqpoXHjs6UC / qKzu2a8t + pc =
= Jpso
-----结束PGP SIGNATURE -----
No, we can''t suppose that. This is not a valid C++ class definition.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.7 (GNU/Linux)
iD8DBQBIFprDx9p3GYHlUOIRAoPKAJ4wfi5RLzo/ysrMPMMYrWm49EVAEQCffZbw
HqpoXHjs6UC/qKzu2a8t+pc=
=Jpso
-----END PGP SIGNATURE-----
你的意思是
虚拟~Base(){/*...*/}
这里?
Did you mean
virtual ~Base() { /*...*/ }
here?
如果Base使用正确的虚拟Base析构函数是正确的(而不是测试
析构函数是无效的)我相信这是格式良好的代码。
-
Jim Langston
您的意思是
虚拟~Base(){/*...*/}
在这里?
Did you mean
virtual ~Base() { /*...*/ }
here?
如果Base使用正确的虚拟Base析构函数是正确的(而不是测试
析构函数是无效的)我相信这是格式良好的代码。
If Base is correct with a proper virtual Base destructor (and not Test
destructor which is invalid) I believe this is well formed code.
形成良好 - 也许。但是代码有[5.3.5 / 3]未定义的行为:
...在第二种方法(删除数组)中如果动态类型为
要删除的对象与其静态类型不同,行为是
undefined。
最佳
Kai-Uwe Bux
Well formed -- maybe. But the code has undefined behavior as per [5.3.5/3]:
... In the second alternative (delete array) if the dynamic type of the
object to be deleted differs from its static type, the behavior is
undefined.
Best
Kai-Uwe Bux
这篇关于通过具有virtualdtor的Base对象删除派生对象的[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!