如果将虚函数或非虚函数添加到C ++中的基类中,是否必须重新编译整个类层次结构? [英] Must the entire class hierarchy be recompiled if a virtual or non-virtual function is added to the base class in C++?

查看:58
本文介绍了如果将虚函数或非虚函数添加到C ++中的基类中,是否必须重新编译整个类层次结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解一个类的vtable在C ++中的敏感程度,为此,我需要了解对于3种更改情况是否需要重新编译整个类层次结构(总共3个头文件)在下面列出.首先,这是我的班级层次结构:

I am trying to learn how sensitive the vtable of a class is in C++ and, for that, I need to know whether recompilation of the entire class hierarchy (total, 3 header files) is necessary for the 3 change-scenarios I list below. First, here is my class hierarchy:

class A {
   public:
   virtual void method1() = 0;
   virtual void method2() = 0;
   virtual ~A() {} 
};

class B : public A {
    public:
    virtual void method1() {};
    virtual void method2() {};
    virtual ~B() {} 
};

class C : public A {
    public:
    virtual void method1() {};
    virtual void method2() {};
    virtual ~C() {} 
};

这是我的情况:

  1. 将非虚拟方法添加到基类A:

  1. A non-virtual method is added to the base class A:

void method3() {};

  • 带有主体的虚拟方法被添加到基类A:

  • A virtual method with a body is added to the base class A:

    virtual void method3() {};
    

  • 一个纯虚拟方法被添加到基类A:

  • A purely virtual method is added to the base class A:

    virtual void method3() = 0;
    

  • 在方案1中,未对vtable进行任何更改.仍然需要重新编译B和C吗?

    In scenario-1, no change to the vtable is made. Is it still required for B and C to be recompiled?

    在方案2中,是否会针对基A重构vtable,从而针对B和C重构vtable?

    In scenario-2, will the vtable be reconstructed for base A, and consequently for B, and C?

    我知道方案3将强制类B和C提供新方法的实现.因此,必须重新编译整个层次结构.

    I know scenario-3 will force classes B and C to provide implementations for the new method. So, the entire hierarchy must be recompiled.

    推荐答案

    C ++一键式规则明确规定,必须将不同翻译单元(即文件)中的实体定义全部定义为 如果您要将它们链接在一起,则完全相同.这样,如果您完全更改了类的定义,则公共,私有, virtual ,非- virtual 任何,所有翻译单元使用该定义的对象必须查看新的类定义.这将需要重新编译.

    The C++ one-definition-rule makes it clear that definitions of entities in different translation units (ie: files) must all be identical if you're going to link them together. As such, if you change the definition of a class at all, public, private, virtual, non-virtual, whatever, all translation units that use that definition have to be looking at the new class definition. And that will require recompiling it.

    此操作失败,但没有诊断信息(链接器错误).因此,您的项目似乎可以很好地链接.确实,它在某些情况下实际上可能有效.但是没有任何东西可以保证它们在哪些情况下可以工作,在哪种情况下不能工作.

    Failure to do this is il-formed, but no diagnostic (linker-error) is required. So your project may appear to link just fine. Indeed, it may actually work in some cases. But there's nothing which guarantees in which cases they will work and in which cases they will not.

    这篇关于如果将虚函数或非虚函数添加到C ++中的基类中,是否必须重新编译整个类层次结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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