Hi
I have written a simple container class named Vector, to check if copy semantics and move semantics are working correctly.
I have inserted code in the the copy ctor, copy assignment, move ctor and move assignment to print a line in an O/P file indicating they have completed.
When testing Vector, I find they are all being invoked except the move ctor.
Here are the relevant parts of Vector. I have listed only the parts relevant for this problem.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
|
class Vector
{
private:
double* elem; // pointer to the elements
int sz; // the number of elements
public:
Vector(int s) // Constructor
{
...
}
Vector(const Vector& a) : // copy constructor
...
{
...
}
Vector& operator=(const Vector& a) // copy assignment
{
...
}
Vector(Vector&& a) : // move constructor
elem { a.elem }, /// 'Grab the elements' from a.
sz { a.sz }
{
/// Now a has no elements.
a.elem = nullptr;
a.sz = 0;
/// fout is an O/P file.
fout << "move constructor completed" << endl;
}
Vector& operator=(Vector&& a) // move assignment
{
...
}
double& operator[](int i) // Element access : subscripting
{
...
}
int size() const // the number of elements
{
return sz;
}
}; /// class
// non-member functions ...
Vector operator+(Vector& a, Vector& b)
{
Vector res(a.size());
for (int i = 0; i < a.size(); ++i)
{
res[i] = a[i] + b[i];
}
return res;
}
|
Here are the relevant portions of the tester:
1 2 3 4 5 6 7
|
Vector v1(5);
/// Adding 2 Vectors (using Vector::operator+()) and getting the result thru a move constructor
void addctor(Vector& x, Vector& y)
{
Vector r(x + y);
}
|
The above statement defines Vector r. It constructs r using the following argument: x + y.
Since the Vector class defines function operator+(), this function gets invoked by the argument. The function result is an rvalue.
Thus the statement boils down to Vector r(Vector&&). Since the Vector class defines a move ctor, it should have been invoked. If the move ctor had been invoked, it should have left the trace "move constructor completed" in the O/P file. No such trace is left there. Therefore, I conclude the move ctor hasn't been invoked.
By comparison, the following code (which should invoke the move assignment) in the tester, does leave an appropriate trace in the O/P file, indicating the move assignment was invoked:
1 2 3 4 5 6
|
/// Adding 2 Vectors (using Vector::operator+()) and getting the result by move assignment
void addassgn(Vector& x, Vector& y)
{
Vector r(5);
r = x + y;
}
|
The copy ctor, copy assgnmnt and move assgnmnt in the tester all get correctly invoked. Only the move ctor doesn't get invoked.
Why is this happening?
Thanks