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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With