Return value optimization and copy elision in C

有些话、适合烂在心里 提交于 2019-11-30 08:03:46

RVO/NRVO are clearly allowed under the "as-if" rule in C.

In C++ you can get observable side-effects because you've overloaded the constructor, destructor, and/or assignment operator to give those side effects (e.g., print something out when one of those operations happens), but in C you don't have any ability to overload those operators, and the built-in ones have no observable side effects.

Without overloading them, you get no observable side-effects from copy elision, and therefore nothing to stop a compiler from doing it.

The reason why it's covered a lot for C++ is because in C++, RVO has side effects (ie. not calling the destructor of the temporary objects nor the copy constructor or assignment operator of the resulting objects).

In C, there's no possible side effect, only potential performance improvements. I see no reason such an optimization couldn't be performed by some compiler. At least, there is nothing that forbids it in the standard.

Anyway, optimization is compiler and optimization level-dependant, so I wouldn't bet on it for critical code paths, unless the compiler used is well defined and not expected to change (which is still often the case).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!