4 ms·
As long as you don't return structs, as the compiler may introduce memcpys here. C doesn't have C++'s RVO, last time I checked many cases that GCC and Clang did
by jcelerier 5y ago
As long as you don't return structs, as the compiler may introduce memcpys here. C doesn't have C++'s RVO, last time I checked many cases that GCC and Clang did optimize in C++ weren't optimized in C.
- pjmlp 5y agoTrue, but still one way I appreciate making C safer is by using poor man's Abstract Data Types with translation units. For the use cases that are too expensive to use functions, macros can be used instead. However that is only if C++ cannot be used at all, otherwise don't bother.
- jacquesm 5y agoThat works, at the expense of possibly hiding bugs in plain sight. Macros are a double edged sword in that sense, you can almost but not quite create a DSL on top of C that is a lot more safe but it has its drawbacks, and you need to be very good at mentally modeling macro expansion to read and debug code like that in order to ensure that it does what it seems to be saying that it will do.
- pjmlp 5y agoAgree, if it is me, I rather use inline functions, but anyway as mentioned only use C when there is no other option.
- tpush 5y agoDo you have an example of that where C++ struct returns are optimized but not C ones?
- jcelerier 5y agoenjoy: https://gcc.godbolt.org/z/7Pn8eqhdK https://gcc.godbolt.org/z/7Pn8eqhdK that's latest GCC, at -O3
- moonchild 5y agoClang does generate good code https://gcc.godbolt.org/z/z781r7Phh https://gcc.godbolt.org/z/z781r7Phh But yes, sadly I think it's still generally advisable to avoid returning large structs by value. Note that this has nothing to do with RVO; as I understand it, RVO is about eliding copy constructors, not actual memory copies, and c has no copy constructors and so gets 'RVO' in all cases.