4 ms·
It's possible that I'm missing something, but I believe that the result is necessarily identical in C, because there can be no observable side-effect of a struc
by stephencanon 8y ago
It's possible that I'm missing something, but I believe that the result is necessarily identical in C, because there can be no observable side-effect of a struct copy in the C abstract machine.
- SidiousL 8y agoI tried to find an example that contradicts what you said, but I can't find any. Here's an online example which can be compiled as both C and C++ and I obtain exactly the same assembly using both clang and gcc. Maybe somebody can tweak this example to force the C compiler not to perform the optimization. https://godbolt.org/g/7Ewun7 https://godbolt.org/g/7Ewun7
- BeeOnRope 8y agoSee my reply to the parent poster for an example where RVO applies in C++ but not C, leading to better code in the C++ case. The key is to let the address of the objects involved escape: otherwise "as if" will let C (and C++ even without RVO) optimize away the copies anyways, since they are not observable in that case.
- 8xde0wcNwpslOw 8y agoDon't quote me on this, but I think padding bytes might have different values in certain cases.
- a1369209993 8y agoI'm fairly sure it's always undefined behavior to observe those differences, so while it's possible in practice, it'd never work in theory.
- e12e 8y ago> while it's possible in practice, it'd never work in theory. Hah, sounds like you nailed the emergent philosophy of C there... :-)
- BeeOnRope 8y agoNo, it is not necessarily identical in C, because even though you don't have constructors or destructors, you can make an address comparison to check whether two objects are identical. For example the following code: https://godbolt.org/g/ikD6bi https://godbolt.org/g/ikD6bi where the address of the caller's variable that will take the return value is passed along to the function returning it. Within the callee, f1 and f2 must be different objects in C, but not in C++. All decent compilers compile this in C++ with only a single object, so sink() will receive identical objects. Most compilers "deoptimize" this in C since sink cannot receive identical objects: two objects are created so f1 and f2 have different addresses, and a copy is performed from f2 to the return value f1. Due to a bug, clang mis-compiles this and applies the C++ RVO to C. So you maybe you are right: you can get RVO in C, but only due to a compiler bug!
- stephencanon 8y agoAh, yes, that's a nice example.