I write a vector. When overloading + operation, problems arise.
template<typename T> Vector<T> Vector<T>::operator +(Vector<T>& v) { Vector<T>* v1 = new Vector<T>(_size + v._size,"temp_v1"); for(int i=0;i<_size;i++) { v1->at(i) = ptr[i]; } for(int i=_size;i<v1->_size;i++) { v1->at(i)=v.at(i-_size); } return *v1; } With Vector<T>* v1 = new Vector<T>(_size + v._size,"temp_v1"); In my understanding, memory is simply allocated for n elements of type Vector<T> , but after return *v1; for it the destructor is called.
int main() { Vector<int> v(0,"v"),v1(0,"v1"); v.push_back(0); v1.push_back(1); Vector<int> v2; v2 = v+v1; std::cout<<v2<<std::endl; } Accordingly, as far as I understood, in v2 refers to 2 elements of the cleared memory block and, when calling the destructor for v2 , the program crashes, referring to double clearing of memory.
Please explain why this is happening and how to fix it.