I am going over A Tour of C++ (Section 5.2 Copy and Move). Following the instructions in the book, I have built a container called Vector
(it mimics std::vector
). My goal is to efficiently implement the following (element-wise) summation:
Vector r = x + y + z;
According to the book, if I don't have move assignment and constructor, +
operator will end up copying Vector
s unnecessarily. So I implemented move assignment and constructor, but I think the compiler still doesn't use them when I run Vector r = x + y + z;
. What am I missing? I appreciate any feedback. Below is my code. I expect to see an output Move assignment
, but I get no output. (The summation part works, it's just the move business that I am not sure)
Code
// Vector.h
class Vector{
public:
explicit Vector(int);
Vector(std::initializer_list<double>);
// copy constructor
Vector(const Vector&);
// copy assignment
Vector& operator=(const Vector&);
// move constructor
Vector(Vector&&);
// move assignment
Vector& operator=(Vector&&);
~Vector(){delete[] elem;}
double& operator[](int) const;
int size() const;
void show();
friend std::ostream& operator<< (std::ostream& out, const Vector& vec);
private:
int sz;
double* elem;
};
Vector operator+(const Vector&,const Vector&);
// Vector.cpp
Vector::Vector(std::initializer_list<double> nums) {
sz = nums.size();
elem = new double[sz];
std::initializer_list<double>::iterator it;
int i = 0;
for (it=nums.begin(); it!=nums.end(); ++it){
elem[i] = *it;
++i;
}
}
Vector::Vector(Vector&& vec) {
sz = vec.sz;
vec.sz = 0;
elem = vec.elem;
vec.elem = nullptr;
std::cout<<"Move constructor"<<std::endl;
}
Vector& Vector::operator=(Vector&& vec) {
if (this == &vec){
return *this;
}
sz = vec.sz;
vec.sz = 0;
elem = vec.elem;
vec.elem = nullptr;
std::cout<<"Move assignment"<<std::endl;
return *this;
Vector operator+(const Vector& vec1, const Vector& vec2){
if (vec1.size() != vec2.size()){
throw std::length_error("Input vectors should be of the same size");
}
Vector result(vec1.size());
for (int i=0; i!=vec1.size(); ++i){
result[i] = vec1[i]+vec2[i];
}
return result;
}
}
// Main
int main() {
Vector x{1,1,1,1,1};
Vector y{2,2,2,2,2};
Vector z{3,3,3,3,3};
Vector r = x + y + z;
} // Here I expect the output: Move assignment, but I get no output.