Re: C aggregate passing (Rust kernel policy)

Jan Engelhardt
2025-02-21T20:06:21Z

On Friday 2025-02-21 19:34, David Laight wrote:
>>
>> Returning aggregates in C++ is often implemented with a secret extra
>> pointer argument passed to the function. The C backend does not
>> perform that kind of transformation automatically. I surmise ABI reasons.
>
>Have you really looked at the generated code?
>For anything non-trivial if gets truly horrid.
>
>To pass a class by value the compiler has to call the C++ copy-operator to
>generate a deep copy prior to the call, and then call the destructor after
>the function returns - compare against passing a pointer to an existing
>item (and not letting it be written to).

And that is why people generally don't pass aggregates by value,
irrespective of the programming language.

>Returning a class member is probably worse and leads to nasty bugs.
>In general the called code will have to do a deep copy from the item
>being returned

People have thought of that already and you can just
`return std::move(a.b);`.

>Then you get code like:
> const char *foo = data.func().c_str();
>very easily written looks fine, but foo points to garbage.

Because foo is non-owning, and the only owner has gone out of scope.
You have to be wary of that.

>You can return a reference - that doesn't go out of scope.

That depends on the refererred item.
string &f() { string z; return z; }
is going to explode (despite returning a reference).

>(Apart from the fact that c++ makes it hard to ensure all the non-class
>members are initialised.)

struct stat x{};
struct stat x = {};

all of x's members (which are scalar and thus non-class) are
initialized. The second line even works in C.