7

I've read that the C++ standard allows optimization to a point where it can actually hinder with expected functionality. When I say this, I'm talking about return value optimization, where you might actually have some logic in the copy constructor, yet the compiler optimizes the call out.

I find this to be somewhat bad, as in someone who doesn't know this might spend quite some time fixing a bug resulting from this.

What I want to know is whether there are any other situations where over-optimization from the compiler can change functionality.

For example, something like:

int x = 1;
x = 1;
x = 1;
x = 1;

might be optimized to a single x=1;

Suppose I have:

class A;

A a = b;
a = b;
a = b;

Could this possibly also be optimized? Probably not the best example, but I hope you know what I mean...

6
  • 4
    I don't agree with the close-vote. This is a real, answerable question. Commented Sep 22, 2011 at 15:24
  • 4
    When eliding copy ctors leads to a bug in your code, then you designed your copy ctor wrong in the beginning. Your code should not depend on how many objects are around, or on how often things are copied/assigned.
    – PlasmaHH
    Commented Sep 22, 2011 at 15:25
  • 1
    Logic in the copy ctor should be logic for copying the object. If it doesn't get copied, then why would copy ctor logic need to run? Commented Sep 22, 2011 at 15:25
  • Both your examples can be optimized to no-op as they don't make any sense.
    – user405725
    Commented Sep 22, 2011 at 15:28
  • Not fully compiler related: computations on floating point numbers may depend on whether or not the intermediate result is stored in a processor register or popped back to the stack, as in the latter case the value is rounded... Commented Sep 22, 2011 at 15:38

6 Answers 6

12

Eliding copy operations is the only case where a compiler is allowed to optimize to the point where side effects visibly change. Do not rely on copy constructors being called, the compiler might optimize away those calls.

For everything else, the "as-if" rule applies: The compiler might optimize as it pleases, as long as the visible side effects are the same as if the compiler had not optimized at all.

("Visible side effects" include, for example, stuff written to the console or the file system, but not runtime and CPU fan speed.)

7
  • +1: "side-effects visibly change." Might be worth expanding on what a visible side-effect actually is.
    – Robᵩ
    Commented Sep 22, 2011 at 15:30
  • 1
    I would note that this were before r-values were introduced. This allowed optimizations. Now that r-values exist, those optimizations are probably not as relevant (copy elision is still faster than a call to the move constructor, but not by the same margin), the behavior was preserved though, not for backward compatibility, but because it still provides a benefit and people have learnt not to use the copy constructor for tricks anyway. Commented Sep 22, 2011 at 15:41
  • @Rob: Would that be enough for your taste?)
    – sbi
    Commented Sep 22, 2011 at 16:23
  • @Matthieu: That's indeed a very valuable addition.
    – sbi
    Commented Sep 22, 2011 at 16:23
  • Thanks, exactly the answer I was looking for. I knew copy constructors can be skipped, I just wanted to know whether other cases exist. Commented Sep 22, 2011 at 20:11
3

It might be optimized, yes. But you still have some control over the process, for example, suppose code:

int x = 1;
x = 1;
x = 1;
x = 1;
volatile int y = 1;
y = 1;
y = 1;
y = 1;

Provided that neither x, nor y are used below this fragment, VS 2010 generates code:

    int x = 1;
    x = 1;
    x = 1;
    x = 1;
    volatile int y = 1;
010B1004  xor         eax,eax  
010B1006  inc         eax  
010B1007  mov         dword ptr [y],eax  
    y = 1;
010B100A  mov         dword ptr [y],eax  
    y = 1;
010B100D  mov         dword ptr [y],eax  
    y = 1;
010B1010  mov         dword ptr [y],eax  

That is, optimization strips all lines with "x", and leaves all four lines with "y". This is how volatile works, but the point is that you still have control over what compiler does for you.

Whether it is a class, or primitive type - all depends on compiler, how sophisticated it's optimization caps are.

Another code fragment for study:

class A
{
private:
    int c;

public:
    A(int b)
    {
        *this = b;
    }
    A& operator = (int b)
    {
        c = b;
        return *this;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    int b = 0;
    A a = b;
    a = b;
    a = b;
    return 0;
}

Visual Studio 2010 optimization strips all the code to nothing, in release build with "full optimization" _tmain does just nothing and immediately returns zero.

1

This will depend on how class A is implemented, whether the compiler can see the implementation and whether it is smart enough. For example, if operator=() in class A has some side effects such optimizing out would change the program behavior and is not possible.

0

Optimization does not (in proper term) "remove calls to copy or assignments". It convert a finite state machine in another finite state, machine with a same external behaviour.

Now, if you repeadly call

a=b; a=b; a=b; 

what the compiler do depends on what operator= actually is. If the compiler founds that a call have no chances to alter the state of the program (and the "state of the program" is "everything lives longer than a scope that a scope can access") it will strip it off. If this cannot be "demonstrated" the call will stay in place.

Whatever the compiler will do, don't worry too much about: the compiler cannot (by contract) change the external logic of a program or of part of it.

-1

i dont know c++ that much but am currently reading Compilers-Principles, techniques and tools

here is a snippet from their section on code optimization:

the machine-independent code-optimization phase attempts to improve intermediate code so that better target code will result. Usually better means faster, but other objectives may be desired, such as shorter code, or target code that consumes less power. for example a straightforward algorithm generates the intermediate code (1.3) using an instruction for each operator in the tree representation that comes from semantic analyzer. a simple intermediate code generation algorithm followed by code optimization is a reasonable way to generate good target code. the optimizar can duduce that the conversion of 60 from integer to floating point can be done once and for all at compile time, so the inttofloat operation can be eliminated by replacing the integer 6- by the floating point number 60.0. moreover t3 is used only once to trasmit its value to id1 so the optimizer can transform 1.3 into the shorter sequence (1.4)

1.3
t1 - intoffloat(60
t2 -- id3 * id1
ts -- id2 + t2
id1 t3

1.4
t1=id3 * 60.0
id1 = id2 + t1

all and all i mean to say that code optimization should come at a much deeper level and because the code is at such a simple state is doesnt effect what your code does

-1

I had some trouble with const variables and const_cast. The compiler produced incorrect results when it was used to calculate something else. The const variable was optimized away, its old value was made into a compile-time constant. Truly "unexpected behavior". Okay, perhaps not ;)

Example:

const int x = 2;
const_cast<int&>(x) = 3;
int y = x * 2;
cout << y << endl;
1
  • Nothing about this is unexpected. const_cast is only for casting away constness of references or pointers, to referred objects that weren't declared const (e.g. when dealing with a bad API or taking a shortcut defining a pair of operator calls). In contrast, the Standard very deliberately states that casting away the constness of a variable that was originally declared const is undefined behaviour. Commented Apr 17, 2016 at 21:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.