Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Isn't return value optimization (RVO) a bug?

I maybe asking a dumb question, but I looked at the wikipedia page for RVO here and could not stop wondering if that behavior is wrong. I tried it in my machine and RVO is fully kicked in despite optimization level. What if there was actually something BIG happenning in a constructor? I know it shouldn't, but what if? I can't understand why RVO would still happen when there are side effects in the constructor.

EDIT: -fno-elide-constructors seems to stop RVO. But the question remains.

EDIT2: On a more serious note, how many people know about something like this? It maybe in the standard, but it is still a really ugly feature as I see it. At least compilers should disable it by default and provide a switch for people who know about this. :)

EDIT 3: I still insist that this is really bad. :). I don't think I know of any other language constraint like this that goes directly against the syntax of language. Everything else throws either compiler or linker errors right?

like image 410
nakiya Avatar asked Oct 11 '10 11:10

nakiya


2 Answers

The standard mandates that operations with concern a program's observable state must not be optimized away, except for copy construction in certain circumstances. You must not rely on copy constructors to be executed, even if they have side effects you expect to see (e.g., console output).

like image 71
sbi Avatar answered Oct 08 '22 00:10

sbi


As said in the other answers, the compiler is allowed optimize away even non trivial copy constructors and assignment operators.

12.8.15

When certain criteria are met, an implementation is allowed to omit the copy construction of a class object, even if the copy constructor and/or destructor for the object have side effects. In such cases, the implementation treats the source and target of the omitted copy operation as simply two different ways of referring to the same object, and the destruction of that object occurs at the later of the times when the two objects would have been destroyed without the optimization. This elision of copy operations is permitted in the following circumstances (which may be combined to eliminate multiple copies):

— in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object with the same cv-unqualified type as the function return type, the copy operation can be omitted by constructing the automatic object directly into the function’s return value

— when a temporary class object that has not been bound to a reference (12.2) would be copied to a class object with the same cv-unqualified type, the copy operation can be omitted by constructing the temporary object directly into the target of the omitted copy

like image 41
DerKuchen Avatar answered Oct 08 '22 01:10

DerKuchen