Suppose I have this hypothetical, odd and unintuitive situation
#include <iostream>
struct A
{
A()
{
member = 1;
}
A(const A &)
{
member = 2;
}
int member;
};
int main()
{
A a = A();
A b = a;
std::cout << a.member << std::endl;
std::cout << b.member << std::endl;
return 0;
}
I know that copy elision means that a will be initialized with just the default constructor and that b will be initialized with the copy constructor. I also know that (on gcc at least) you can tell the compiler not to do any copy elision.
My question is there some way of having the compiler not use copy elision just for this class?
I realize that the answer in any real situation will be to find some other way 99.9% of the time, and I don’t have one of those 0.01% cases (this is an actual hypothetical question, not a “hypothetical question”)
Copy elision is allowed by the standard and it is the single optimization that is not required to follow the As-If rule[#1], So you should not rely on the behavior.
You might use some compiler settings like in case of gcc, from the man page:
-fno-elide-constructorHowever, using this makes your code non portable across different compilers.
[#1] C++03 1.9 “Program execution:
The footnote further describes it in detail.