将纯虚拟更改为虚拟并保持二进制兼容

发布于 2024-11-25 01:54:02 字数 73 浏览 6 评论 0原文

我可以将纯虚函数(在基类中)更改为非纯函数,而不会遇到任何二进制兼容性问题吗? (Linux、GCC 4.1)

谢谢

Can I change a pure-virtual function (in a base class) to become non-pure without running into any binary compatibility issues? (Linux, GCC 4.1)

thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

零度° 2024-12-02 01:54:02

当您从纯虚拟切换到虚拟然后重新编译代码时,不存在兼容性问题。 (但是,virtual 到纯 virtual 可能会导致问题。)

您唯一应该注意的是,非纯 virtual 方法必须有身体。它们不能一直得不到实施。即

class A {
public:
  virtual int foo ()
  {
    return 0; //put some content
  }
};

你不能简单地说,

virtual int foo();

它会导致链接器错误,即使你不使用它。

There is no compatibility issues when you switch from pure virtual to virtual and then re-compile the code. (However, virtual to pure virtual may cause problems.)

The only thing you should take care is, that the non-pure virtual methods must have a body. They cannot remain unimplemented. i.e.

class A {
public:
  virtual int foo ()
  {
    return 0; //put some content
  }
};

You cannot simply put like,

virtual int foo();

It will cause linker error, even if you don't use it.

不乱于心 2024-12-02 01:54:02

保持二进制兼容性对您来说意味着什么?

对象布局将是相同的,但除非重新编译所有代码,否则您将违反单一定义规则,此时二进制兼容性基本上毫无用处。如果不重新编译,ODR 就会被破坏,虽然它可能可以工作,但也可能无法工作。

特别是,如果类中的所有虚拟方法都是纯方法或内联定义的,则编译器可能会在包含标头的每个翻译单元中生成 vtable,并将其标记为弱符号。然后链接器将选择其中之一并丢弃所有其他。在这种情况下,链接器不需要验证所有 vtable 是否完全相同,并且会随机选择一个(或以未定义的方式确定性地),并且它可能会选择一个这样的 vtable,其中该方法是纯虚拟的,这在如果在基类的对象上调用该方法,turn 可能最终导致应用程序崩溃。

What does it mean to maintain binary compatibility to you?

The object layout will be the same, but you will be breaking the One Definition Rule unless you recompile all code, at which point binary compatibility is basically useless. Without recompiling, then the ODR is broken, and while it might be the case that it works, it might also not work.

In particular if all of the virtual methods in the class are either pure or defined inline, then the compiler might generate the vtable in each translation unit that includes the header and mark it as a weak symbol. Then the linker will pick one of them and discard all the others. In this situation the linker is not required to verify that all of the vtables are exactly the same and will pick one at random (or deterministically in an undefined way), and it might pick one such vtable where the method is pure virtual, which in turn might end up crashing the application if the method is called on an object of the base class.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文