Everyone.
I have a problem. I want to sum two vectors by overloading operator +, and assign result to third vector. But when i sum values of two vectors i save results in temporary vector, and in the end i return that vector. But when sums are done that temporary vector calls destructor and values are deallocated. How can i solve that problem?
P.S I have some problem with other operators. But i'm thinking salvation for others will be the same.
// Vector class definition
template <class T> class Vector
{
private:
unsigned x; // used to store size of vector
T *vector;
public:
Vector();
Vector(unsigned x);
Vector(std::initializer_list<T> list);
~Vector();
void random(T min, T max);
void resize(unsigned x);
unsigned size(void);
T &front(void);
T &back(void);
void operator*=(Vector<T> &vector);
void operator/=(Vector<T> &vector);
void operator%=(Vector<T> &vector);
void operator+=(Vector<T> &vector);
void operator-=(Vector<T> &vector);
Vector<T> operator*(Vector<T> &vector);
Vector<T> operator/(Vector<T> &vector);
Vector<T> operator%(Vector<T> &vector);
Vector<T> operator+(Vector<T> &vector);
Vector<T> operator-(Vector<T> &vector);
T &operator[](int i);
};
/* Vector Constructors */
template <class T> Vector<T>::Vector()
{
}
template <class T> Vector<T>::Vector(unsigned x)
{
Vector::x = x;
Vector::vector = new T[Vector::x];
}
template <class T> Vector<T>::Vector(std::initializer_list<T> list)
{
Vector::x = list.size();
Vector::vector = new T[Vector::x];
auto it = list.begin();
for(int i = 0; i < Vector::x; i++, it++)
Vector::vector[i] = *it;
}
/* Destructor */
template <class T> Vector<T>::~Vector()
{
delete[] Vector::vector;
}
template <class T> void Vector<T>::random(T min, T max)
{
assert(std::is_arithmetic<T>::value);
std::random_device rd;
std::mt19937 eng(rd());
if constexpr(std::is_floating_point<T>::value)
{
std::uniform_real_distribution<T> dist(min, max);
for(int i = 0; i < Vector::size(); i++)
Vector::vector[i] = dist(eng);
}
else
{
std::uniform_int_distribution<T> dist(min, max);
for(int i = 0; i < Vector::size(); i++)
Vector::vector[i] = dist(eng);
}
}
template <class T> Vector<T> Vector<T>::operator+(Vector<T> &vector)
{
assert(Vector::size() == vector.size());
Vector<T> output(Vector::size());
for(int i = 0; i < Vector::size(); i++)
output[i] = Vector::vector[i] + vector[i];
return output; // after this line output vector is deallocated :(
}
int main(int argc, char *argv[])
{
Vector<float> *vector1 = new Vector<float>(3);
Vector<float> *vector2 = new Vector<float>(3);
Vector<float> *vector3 = new Vector<float>;
vector1->random(-1.0f, 1.0f);
vector2->random(-1.0f, 1.0f);
*vector3 = *vector1 + *vector2;
delete vector1;
delete vector2;
delete vector3; // here's SIGABORT results, even if vectors are not pointers (they will be deallocated before return anyway)
return 0;
}