I have the numeric vector template class below (vector for numerical calculations). I am trying make it possible to write D=A+B+C
where all variables are Vector
objects. A
, B
and C
should not be modified. My idea is to use Vector operator+(Vector&& B)
so that after (hopefully) an Rvalue Vector
has been returned from B+C
, all subsequent additions are stored in that object i.e. steal the storage of the Rvalue for all subsequent additions. This is in order to eliminate creation of new objects and required storage.
My problem is that I can see from output statements from each function called that Vector operator+(Vector&& B)
is never called. I cannot understand why since if I have an overloaded dummy function foo(Vector& B)
and foo(Vector&& B)
and try foo(A+B+C)
, then the second function is called exactly as I hoped.
Sorry for the long winded question but this is my first question here and I want to try to be as clear as possible.
Any suggestions as to what I am obviously doing wrong or why I should not be trying this, would be appreciated.
template <typename T>
class Vector
{
int n;
T* v;
Vector();
~Vector();
Vector(const Vector& B);
Vector(Vector&& B);
inline Vector operator+(const Vector& B) const;
inline Vector operator+(Vector&& B) const;
};
template <typename T>
Vector<T>::Vector(const Vector<T>& B)
{
...
}
template <typename T>
Vector<T>::Vector(Vector<T>&& B)
{
...
}
template <typename T>
Vector<T> Vector<T>::operator+(const Vector<T>& B) const
{
Vector<T> C;
...
return C;
}
template <typename T>
Vector<T> Vector<T>::operator+(Vector<T>&& B) const
{
...do stuff to B
return B;
}