On 08/05/2023 17:49,
Mut...@dastardlyhq.com wrote:
> On Thu, 20 Apr 2023 16:59:59 +0200
> David Brown <
david...@hesbynett.no> wrote:
>> Perhaps you got that idea from working with old C compilers and old C
>> code, where programmers were allergic to creating structs and would
>> rather use an ugly and error-prone mix of pointer parameters instead of
>> returning the function's results in the natural way - as the return value.
>>
>> When a function (C or C++) returns a struct that is too big to fit in
>> registers, it is implemented by the calling function passing a hidden
>> pointer parameter for the return value - there's no need to do it
>> manually. C++ RVO guarantees you avoid extra coping in many cases.
>
> In many cases is not every case so you could end up with performance in the
> toilet on certain architectures all because you want to be "pure" and not use
> pointers/references.
Again - when you have a function (C or C++) that returns a struct that
is too big to fit in registers, it is handled as though the caller had
passed a pointer to a struct to fill up. There will be, at most, minor
differences in the generated code. But if the struct is small enough to
fit in registers (and the ABI supports that), returning a struct will be
more efficient.
I agree that "many cases" is not "every case" - that's why I wrote "many
cases", and not "every case".
>
> Also C++ can't change the hardware and if a C++ compiler can optimise returns
> so can a C compiler.
>
Yes, so you get the same effects with C and C++, as I said. RVO and
copy elision guarantee (C++17) or allow (earlier C++) skipping of
unnecessary copy or move constructors and destructors when returning a
struct or class.
<
https://en.cppreference.com/w/cpp/language/copy_elision>
>> If the data is big enough that you don't want it in your local frame,
>> you'll likely be using some kind of ownership class to handle the
>> resource and heap management in a clean RAII manner.
>
> ie globals in disguise. Which is fine, but don't pretend its some profoundly
> new paradigm.
>
No, that is not "globals in disguise". And of course it is not a new
idea - RAII for tracking memory is one of the main reasons for the
existence of C++.