I know there are plenty of discussions about this topic, like this famous one (see sbi's answer). My goal is to overload the operator + for two vectors, starting from the operator +=, as explained in the linked famous question.
The following code snippet is quite classical
#include <iostream>
#include <cmath>
template <typename T>
class vector{
private:
T* elem;
std::size_t _size;
public:
vector(const std::size_t size) : elem{new T[size]}, _size{size} {}
~vector(){ delete[] elem;}
std::size_t size() const { return _size;}
T& operator[](std::size_t i){ return elem[i];}
const T& operator[](std::size_t i) const{ return elem[i];}
vector& operator+=(const vector& b) ;
vector& operator=(vector b);
};
template <typename T>
std::ostream& operator<<(std::ostream& os, const vector<T>& v) {
for (auto i = 0u; i < v.size(); ++i)
os << "v[" << i << "] = " << v[i] << std::endl;
return os;
}
template <typename T>
vector<T>& vector<T>::operator+=(const vector<T>& b) {
for (std::size_t i =0;i<_size;++i){
elem[i]+=b[i];
}
return *this;
}
template <typename T>
vector<T> operator+(vector<T> a,const vector<T>& b){
a+=b;
return a;
}
template <typename T>
vector<T>& vector<T>::operator=(vector<T> b){
std::swap(*this,b);
return *this;
}
int main(){
vector<double> v{10};
vector<double> w{10};
for (auto i=0u;i<v.size();++i){
v[i] = i;
w[i] = i*i;
}
v+=w;
std::cout << v << std::endl;
vector<double> v1{10};
v1 = w + v;
std::cout << v1 << std::endl;
return 0;
}
After I compile, I obtain several warnings, and when I execute I obtain the following error
free(): double free detected in tcache 2 Aborted (core dumped)
and I can't undertand neither where it happens, nor how to fix it. I'm trying to stick as much as I can to the suggestions in the linked topic, but there's some bug in my overloading procedure, and I can't spot where/why.