Etienne Dechamps
Etienne Dechamps

Reputation: 25351

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

Consider the following C++ code:

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 (e.g. int c), and initialize it in foobar(), will existing applications which call foobar() break? Note that this is about binary compatibility, not source compatibility.

Upvotes: 1

Views: 1195

Answers (2)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272667

It depends entirely on what your compiler chooses to do (more specifically, what the platform ABI dictates).

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.

Upvotes: 3

Andrew White
Andrew White

Reputation: 53516

Since the size of X would change, yes. Arrays and such depend on sizes. You might get "lucky" and padding might allow older apps to use the newer lib but it would be pure luck.

Upvotes: 3

Related Questions