为什么必须定义未使用的虚拟功能? [英] Why must unused virtual functions be defined?

查看:136
本文介绍了为什么必须定义未使用的虚拟功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得很奇怪,未使用的虚拟函数仍然必须定义,而不像未使用的普通函数。我对于创建类对象时创建的隐式的 vtables vpointers 有所了解,这有点回答了这个问题(即必须定义该函数以便指向虚函数可以被定义),但是这会将我的查询进一步推回。

I find it quite odd that unused virtual functions must still be defined unlike unused ordinary functions. I understand somewhat about the implicit vtables and vpointers which are created when a class object is created - this somewhat answers the question (that the function must be defined so that the pointers to the virtual function can be defined) but this pushes my query back further still.

为什么如果绝对没有虚拟函数被调用的可能性,那么需要为函数创建一个 vtable 条目 p>

Why would a vtable entry need to be created for a function if there's absolutely no chance that virtual function will be called at all?

class A{
    virtual bool test() const;
};

int main(){
    A a; //error: undefined reference to 'vtable for A'
}

即使我声明 A :: test()它在程序中从未使用过,但它仍然抛出一个错误。编译器是否可以不运行该程序,并且实现 test()从未被调用 - 因此不需要 vtable 条目?或者是对编译器的期望是不合理的?

Even though I declared A::test() it was never used in the program but it still throws up an error. Can the compiler not run through the program and realise test() was never called - and thus not require a vtable entry for it? Or is that an unreasonable thing to expect of the compiler?

推荐答案

因为这将不可避免地成为一个非常难以解决的问题编译器作者的一部分,当能够离开虚函数的有用性未定时,至多是可疑的。编译器作者肯定有更好的问题需要解决。

Because it would inevitably be a very difficult problem to solve on the compiler writer's part, when the usefulness of being able to leave virtual functions undefined is at best dubious. Compiler authors surely have better problems to solve.

另外,即使您不调用它,您也正在使用该函数。您正在使用它的地址。

Besides, you ARE using that function even though you don't call it. You are taking its address.

这篇关于为什么必须定义未使用的虚拟功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆