简体   繁体   English

C++ 和二进制兼容性:按值返回 POD 结构

[英]C++ and binary compatibility: returning a POD struct by value

Consider the following C++ code:考虑以下 C++ 代码:

struct X
{
        int a;
        int b;
};

X foobar()
{
        X x = { 1, 2 };
        return x;
}

Now assume this code is put in a shared library, which is used by third-party applications.现在假设这段代码被放在一个共享库中,供第三方应用程序使用。

My question is: if I add another member at the end of X (eg int c ), and initialize it in foobar() , will existing applications which call foobar() break?我的问题是:如果我在X的末尾添加另一个成员(例如int c ),并在foobar()中对其进行初始化,调用foobar()的现有应用程序会中断吗? Note that this is about binary compatibility, not source compatibility.请注意,这是关于二进制兼容性,而不是源代码兼容性。

It depends entirely on what your compiler chooses to do (more specifically, what the platform ABI dictates).这完全取决于您的编译器选择做什么(更具体地说,平台 ABI 规定的内容)。

You can imagine that if the return value is placed on the stack, you would now be writing more onto the stack than the caller is expecting, which may result in stamping on something.您可以想象,如果将返回值放在堆栈上,那么您现在在堆栈上写入的内容将比调用者预期的要多,这可能会导致在某些东西上加盖印记。

In general, you shouldn't rely on any particular behaviour.一般来说,你不应该依赖任何特定的行为。 You simply must re-compile the client applications.您只需重新编译客户端应用程序。 The only realistic alternative is something like the PIMPL idiom .唯一现实的选择是像PIMPL idiom之类的东西。

Since the size of X would change, yes.由于 X 的大小会改变,是的。 Arrays and such depend on sizes. Arrays 等取决于尺寸。 You might get "lucky" and padding might allow older apps to use the newer lib but it would be pure luck.您可能会得到“幸运”,并且填充可能允许旧应用程序使用较新的库,但这纯粹是运气。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM