I'm trying to make me clear about move semantics. I'm following examples of the Bjarne Stroustrup book 4th edition and I'm really lost.
He says that copy of objects can be expensive when a lot of elements (in class vector) so move semantics is the solution.
Think something like:
Vector result = vector1 + vector2 + vector3;
Order may be wrong but it will do (vector2 + vector3) generating partial result result1, and result1 + vector1, generating result;
I overloaded operator+:
Vector operator+(const Vector &a,const Vector &b)
{
if(a.size()!=b.size()) {
throw length_error{"Length of vectors must match for summing"};
}
Vector result(a.size());
cout << "Intermediate result for sum created" << endl;
for(long unsigned int i=0; i<result.size();i++){
result[i] = a[i] + b[i];
}
return result;
}
I also created a move constructor:
Vector::Vector(Vector&& orig) noexcept
:elem{orig.elem},
sz{orig.sz}
{
cout << "Move constructor called" << endl;
orig.elem = nullptr; // We own the array now
orig.sz = 0;
}
So no copy operations are performed. But there are some things I don't understand. One is related to just c++ and the other to c++11.
So first:
As you can see, when operator+ exits Vector result should be destroyed. But not after the contents are copied to another instance of vector. What I called partial result1.
This never happens, the output of the program is like this:
- New class vector created <-- Constructor of partial result 1
- Intermediate result for sum created <-- Operator+ applied
- New class vector created <-- Constructor of partial result 2 -> goes to result
- Intermediate result for sum created <-- Operator+ applied
- Class vector destroyed <-- I undenderstand that partial result 1 destroyed.
But I don't see the second partial result destroyed until the end of the program. Nor I see any copy operations (I have done operator= and copy constructor).
So I don't understand that. If the scope of the variable Vector result is inside operator+ the contents MUST be copied to another variable. That's not done. It seems that last result of the sum is just assigned to Vector result of the sum.
Second:
No move operations are performed. I cannot get move semantics to work here. I took a look to http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52745 and applied what's there but no move operations anyway.
Every result is right.
So clearly, there is something I'm doing wrong.
You can grab the whole code (with autotools config + eclipse) from here:
http://static.level2crm.com/cx11-learn-20140218.tar.bz2
Can someone explain what happens here?
Best regards,