Is return value optimization (RVO) an error?

I may be asking a stupid question, but I looked at the wikipedia page for RVO here and couldn't stop wondering if this behavior was wrong. I tried this on my machine and RVO kicked completely, despite the level of optimization. What if there was something BIG in the constructor? I know this should not, but what if? I canโ€™t understand why RVO will happen anyway when side effects occur in the constructor.

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

EDIT2: More importantly, how many people know about something like this? It may be in the standard, but it is still a very ugly function, as I see it. At the very least, compilers should disable it by default and provide a switch for people who know about it. :)

EDIT 3: I still insist that this is really bad. :). I donโ€™t think I know of any other language restriction like this, directly against the syntax of the language. Does everything else throw compiler or linker errors?

+7
c ++ return-value-optimization
source share
3 answers

The standard requires that operational actions with the program the observed state should not be optimized, with the exception of the copy design in certain circumstances. You should not rely on executable copy constructors, even if they have side effects that you expect to see (for example, console output).

+20
source share

As other answers say, the compiler even allows optimization of non-trivial copy constructors and assignment operators.

12/08/15

When certain criteria are met, implementations are allowed to omit the copy construct of the class object , even if the copy constructor and / or destructor for the object have side effects . In such cases, the implementation considers the source and purpose of the omitted copy operation as just two different ways of accessing the same object, and the destruction of this object occurs in later times, when two objects would be destroyed without optimization. This permission of copy operations is allowed in the following cases (which can be combined to eliminate multiple copies):

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

- when an object of a temporary class that was not attached to a link (12.2) is copied to a class object with the same cv-unqualified type, the copy operation can be omitted by creating a temporary object directly to the target of the missed copy

+13
source share

Define "wrong." The C ++ language explicitly allows this optimization, even if it is observable. If the behavior of your program depends on a specific implementation, then, unfortunately, you are not using ISO C ++, but some dialect.

+7
source share

All Articles