I am trying to demonstrate the usefulness of move constructors in eliminating unnecessary copying. However, when I run in Release, the visual studio optimizer elids the copy. No copy constructor is called when a move constructor is not available, and obviously move-constructor is not called when one is added.
I can remove the optimizations by running in Debug, but this does not make for a very convincing demonstration for the need for move semantics.
struct A {
int *buff;
A() {
cout << "A::constructor\n";
buff = new int[1000000];
}
A(const A& a) {
cout << "A::copy constructor\n";
buff = new int[1000000];
memcpy(buff, a.buff, 1000000*sizeof(int));
}
A(A&& original)
{
cout << "Move constructor" << endl;
buff = original.buff;
original.buff = nullptr;
}
~A() { cout << "A::destructor\n"; delete[] buff; }
};
A getA()
{
A temp;
temp.buff[0] = 2;
return temp;
}
void useA(A a1) {
cout << a1.buff[0] << endl;
}
void main() {
useA(getA()); // i'd like copy-constructor to be called if no move constructor is provided
}
Is there anything I can change in the code to prevent the optimizer from being able to do away with the copy, and show how adding a move constructor can prevent a full copy?
Edit: Preferably the demonstration should NOT require an explicit move call/cast.