I'm trying to build my own Matrix class and have overloaded the "*=" operator. I am however running into problems with some pointer loss. I don't understand where my problem is at the moment.
Is it because I'm creating a new Matris "new_m" and this only lives inside the scope of the function? So I can't set the new pointer to data to the implied (*this)
object?
Below is the code for my *=
operator.
Matris<T> &operator*=(const Matris<T> &m){
//if(m_cols != m.m_rows || m.rows != m.m_cols) throw new std::out_of_range("When multiplying two matrices they have to have be \"opposites\", that is one can be 1x2 and other one 2x1.");
//else{
unsigned int new_cap = m_rows * m.m_cols;
Matris<T> new_m(sqrt(new_cap));
new_m.m_vec = (T*) realloc(new_m.m_vec, new_cap*sizeof(T));
std::memset (new_m.m_vec, 0, sizeof(T) * new_cap);
for(size_t i = 0; i < m_rows; i++){
for (size_t j = 0; j < m.m_cols; j++) {
for (size_t k = 0; k < m_cols; k++) {
new_m(i,j) += (*this)(i,k) * m(k,j);
}
}
}
m_vec = new_m.m_vec;
//}
return *this;
}
And this is how I store and save my data in my Matris class:
private:
size_t m_rows;
size_t m_cols;
size_t m_capacity;
T * m_vec;
This is the constructor that is being called with an int:
explicit Matris(const unsigned int i){ //constructor with one integer, has to be integer, can't be negative or float.
m_rows = i;
m_cols = i;
m_capacity = i*i;
m_vec = (T*) malloc(i*i*sizeof(T));
std::memset (m_vec, 0, sizeof (T) * i*i);
}
m_vec = new_m.m_vec;
This makes m_vec
point to part of the temporary object that's about to be destroyed. You want:
*this = new_m;
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments