Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this code well-defined regardless of copy elision?

Consider this code:

#include <iostream>

struct Test
{
    int x;
    int y;
};

Test func(const Test& in)
{
    Test out;
    out.x=in.y;
    out.y=in.x;
    return out;
}

int main()
{
    Test test{1,2};
    std::cout << "x: " << test.x << ", y: " << test.y << "\n";
    test=func(test);
    std::cout << "x: " << test.x << ", y: " << test.y << "\n";
}

One would expect an output like this:

x: 1, y: 2
x: 2, y: 1

and this is indeed what I get. But due to copy elision, could out be in the same place in memory as in and result in the last line of output being x: 2, y: 2?

I've tried compiling with gcc and clang with both -O0 and -O3, and the results still look as intended.

like image 950
Ruslan Avatar asked Oct 23 '15 14:10

Ruslan


1 Answers

No, it can not. Optimizations can not break well-formed code, and this code is well-formed.

EDIT: Small update. Of course, my answer assumes the compiler itself is bug-free, which of course is something you can only pray for :)

EDIT2: Some people are talking about side-effects in copy constructors and that they are bad. Of course, they are not bad. They way I see it, is that in C++ you are not guaranteed to have a known number of temporary objects created. You are guaranteed that every temporary object created will be destroyed. While optimizations are allowed to reduce the number of temporary objects by doing copy elision, they are also allowed to increase it! :) As long as your side-effects are coded with this fact in mind, you are good.

like image 192
SergeyA Avatar answered Sep 17 '22 14:09

SergeyA