虚拟接口Dtor &&动态_Cast
我试图从接口向下转换为派生类,但我的虚拟 dtor 杀死了它?
class IFOO
{
public:
virtual ~IFOO(){};
virtual size_t index() PURE;
};
class FOO : public IFOO
{
public:
FOO() : size(5){};
~FOO(){};
virtual size_t index(){ return index; };
size_t index;
};
int main() {
IFOO* A = &FOO();
FOO* B = dynamic_cast< FOO* >( A );
return 0;
}
为什么会这样呢?
I'm trying to downcast from an interface to a derived class but my virtual dtor kills it?
class IFOO
{
public:
virtual ~IFOO(){};
virtual size_t index() PURE;
};
class FOO : public IFOO
{
public:
FOO() : size(5){};
~FOO(){};
virtual size_t index(){ return index; };
size_t index;
};
int main() {
IFOO* A = &FOO();
FOO* B = dynamic_cast< FOO* >( A );
return 0;
}
Why is this so?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在行中获取临时地址。
我猜如果您从界面中删除 dtor,代码就可以
工作,因为在这种情况下,它将不会被调用,并且您进入了未定义行为的领域,其中任何内容这是可能的,即使是糟糕的代码也能按预期工作。
另外,我建议您不要将类名全部大写,因为这通常是宏的约定(除非您的类名是宏,但当然不可能)。另外,不要使用宏 (
PURE
) 来使函数成为纯虚函数,这会让 95% 可能需要阅读您的代码的人感到困惑。You are taking the address of a temporary in the line
It should be
I guess the code works if you remove the dtor from your interface, because in that case it will not be called, and you enter the realm of undefined behavior, in which anything is possible, even bad code working as expected.
Also, i would recommend that you do not write your class names in all capitals, because that is usually the convention for macros (unless your class names are macros, but surely, that cannot be). Also, don't use a macro (
PURE
) to make functions pure virtuals, this confusing 95% of the people that might have to read your code.