Assignment operator and copy constructor after matricies multiplication - c++

Have problem with copy constructor and assignment operator. Have written code to multiply matricies:
Matrix& Matrix::operator * (const Matrix &second) const
{
// Create result matrix
Matrix result(Rows(), second.Columns());
// Multiply matricies
for (unsigned i = 0; i < Rows(); i++)
{
for (unsigned j = 0; j < second.Columns(); j++)
{
result[i][j] = 0.0;
for (unsigned k = 0; k < Columns(); k++)
{
result[i][j] += m_matrix[i][k] * second[k][j];
}
}
}
return result;
}
In Main code I call the operator:
Matrix C = A * B;
However code destroys result variable before assignment, how to write such code correctly to return result matrix? Copy constructor is:
Matrix::Matrix(const Matrix& matrix)
{
AllocateMatrixArray(matrix.Rows(), matrix.Columns());
CopyMatrixData(matrix);
}
Assignment operator is:
Matrix& Matrix::operator = (const Matrix& other)
{
AllocateMatrixArray(other.Rows(), other.Columns());
CopyMatrixData(other);
return *this;
}
However I see that compiler does not use it - copy constructor is enough.

Your code returns a reference to a local variable, which will be destroyed at the end of the function's scope. Don't do that:
Matrix Matrix::operator * (const Matrix &second) const {
// same as above
}
Note that the return value is now a Matrix instead of a Matrix&.

You should not be returning a reference to local variable. By convention the opertor*(I mean the two argument version of course) returns a copy to the result. Same holds true for the other operations like operator+, operator- and so on. A reference is returned by the moifying versions of those operators like operator *=, operator += and so on.

If you want to write expressions like C = A*B all C A and B must be "values".
So the return value of operator* must be matrix and not matrix&, espscialy if the & refers to a local variable (like result) thet will be destroyed at } (hence before = is executed).
That said, there are some more issues:
The sample Matrix C = A*B is not an assignment: an assignment happens the the value of an already existent object is changed. But Matrix C is created contextually: in fact, what it is called here, is the Matrix constructor (copy constructor, in this case)
There could be memory leaks: Although I don't see how the matrices data are handled, your operator=
seems to allocate new space and then copy the data in it. But what happens to the space containing the old data? Does it remain forgotten around? Is is automatically released by a smart pointer?
Similarly, just like = should dismiss the old data, also the class itself should dismiss its own data on destruction, hence a destructor should also be implemented. Otherwise every time a Matrix is dismissed (like the local result), its data will stay around.

Related

Change value pointed by this pointer

I wrote this working piece of code for my matrix struct. It computes the value of a square matrix raised to the e-th power, but this is irrelevant. I want to know what is happening in the last lines.
Is the value of p being copied to the location pointed by this? Is it a shallow copy or a deep copy?
Is this being changed? I don't think so because it's const.
How can I implement that copy to make it run faster?
matrix& operator ^=(int e)
{
matrix& b = *this;
matrix p = identity(order());
while (e) {
if (e & 1)
p *= b;
e >>= 1;
b *= b;
}
*this = p;
return *this;
}
One of the following will make it faster, if you're added appropriate buffer-stealing support to your class:
Replace
*this = p;
by either (preferred in C++11)
*this = std::move(p);
or (for C++03, should still work ok in C++11)
swap(p); // if swap is a member
swap(*this, p); // if it's not
However, since you can't overwrite the left hand side in place, best is to implement operator^, and write operator^= in terms of that:
matrix operator^(const matrix& b, int e)
{
matrix p = identity(b.order()); // move or elision activated automatically
while (e) {
if (e & 1)
p *= b;
e >>= 1;
b *= b;
}
return p; // move or NRVO activated automatically
}
matrix& operator^=(int e)
{
*this = (*this) ^ e; // move activated automatically since RHS is temporary
// ((*this) ^ e).swap(*this); in C++03
return *this;
}
Just noticed you are overwriting *this in place, with successive squares.
*this = p; invokes your matrix's operator=(matrix) method, if it has one, otherwise it invokes a compiler-generated operator=() that simple performs a member-by-member copy of p's fields into this's fields (using their respective operator=() implementations).

Overloaded operator C++: Object = Object * Object

I'm having trouble multiplying objects using the overloaded * operator
In the class I have the operator defined as:
const Matrix operator*(Matrix& B);
The implementation is
const Matrix Matrix::operator* (Matrix& B){
Matrix r = Matrix(B.M,B.N);
for(int i = 0; i < r.M; i++){
for(int j = 0; j < r.N; j++){
r.data[i*N+j] = (*this)(i,j) * (int)B(i,j);
}
}
return r;
}
When I call
Matrix C = A * B
I will get the expected result, however calling
C = C * C
Results in an error.
I'm guessing it's to with the calling object C but I'm not sure what to do!
EDIT:
My assignment operator. Matrix R is a deep copy.
Matrix Matrix::operator=(Matrix& B){
Matrix r(M,N);
for(int i = 0; i < M; i++){
for(int j = 0; j < N; j++){
r.data[i*N+j] = B(i,j);
}
}
return r;
}
The error is because you are storing your data in a variable called "data" (which is an int[] on the heap) and you haven't overridden your assignment operator to copy the values from the object being copied into the current member variable "data". So, the default assignment operator will copy the "data" pointer for you, which in your case is from a temporary value that will be out of scope after the assignment. Your destructor will most likely delete the "data" variable you are now pointing to because the temporary goes out of scope.
You have defined your own copy constructor to establish the "data" variable on the heap. The first example you have where Matrix C = A * B will use that copy constructor, which works.
The second example uses the default assignment operator, which will only copy the data pointer from the temporary value returned from the operation. Thus, you basically have no value that data is pointing to.
You have to define an assignment operator to make this work.
Here are suggested functions to go along with your copy constructor:
void Matrix::swap(Matrix& other)
{
std::swap(M, other.M);
std::swap(N, other.N);
std::swap(data, other.data);
}
Matrix& Matrix::operator= (Matrix matrix)
{
swap(matrix);
return *this;
}
Matrix Matrix::operator* (const Matrix& B)
{
Matrix r = Matrix(B.M,B.N);
for(int i = 0; i < r.M; i++){
for(int j = 0; j < r.N; j++){
r.data[i*N+j] = (*this)(i,j) * (int)B(i,j);
}
}
return r;
}
This works well because the copy constructor will be used for "matrix" in assignment operator (operator=). Then, the swap function will trade the "data" array with the temporary copy of Matrix. Therefore, you will copy the appropriate "data" from the operation*'s temporary variable.
This has nothing to do with "calling object C".
The first version
Matrix C = A * B;
uses constructor(s) or class Matrix to initialize new object C.
The second version
C = C * C;
uses assignment operator of class Matrix to assign new value to an existing object C.
You managed to screw up the assignment operator declaration/implementation somehow (which you don't show in the code you posted), which is why the second version does not compile.
There are problems with your operator * declaration as well. Even if you want to have it as class member, a more meaningful way to declare it would be
Matrix Matrix::operator* (const Matrix& B) const {
...
Note how const qualifiers are placed.
EDIT: So, here's your problem. Your assignment operator is completely broken.
Firstly, you declared your assignment operator as
Matrix Matrix::operator=(Matrix& B)
This operator cannot accept temporary objects on the right-hand side because you failed to declare the parameter as const. Non-const references cannot be bound to temporary objects. And in C = C * C the right-hand side of assignment is actually a temporary object produced by *operator.
Redeclare your assignment operator as
Matrix &Matrix::operator=(const Matrix& B)
Note, it accepts a const reference and returns a reference.
Secondly, your assignment operator is supposed to assign to *this, not to some standalone temporary object. And it is supposed to return a reference to *this. In other words, the implementation should be something along the lines of
Matrix &Matrix::operator=(const Matrix& B){
// Resize `*this` to match the size of `B`
for(int i = 0; i < M; i++){
for(int j = 0; j < N; j++){
this->data[i*N+j] = B(i,j);
}
}
return r;
}
Try to define the operator like this:
Matrix operator* (const Matrix& x, const Matrix& y)
{
//...
}

C++ Destructor being called in overloaded arithmetic operators

I have a custom-made Matrix library for a neural network program and overloaded arithmetic operators.
Here's the class declarations:
class Matrix{
public:
int m;
int n;
double **mat;
Matrix(int,int);
Matrix(int);
Matrix(const Matrix& that):mat(that.mat),m(that.m),n(that.n)
{
mat = new double*[m];
for(int i = 0;i<m;i++)mat[i] = new double[n];
};
~Matrix();
friend istream& operator>>(istream &in, Matrix &c);
friend ostream& operator<<(ostream &out, Matrix &c);
Matrix operator+(const Matrix& other);
};
This is the function definition for + operation:
Matrix Matrix::operator+(const Matrix& other)
{
Matrix c(m,n);
for(int i=0;i<m;i++)
{
for(int j = 0; j<n;j++)
c.mat[i][j] = mat[i][j] + other.mat[i][j];
}
return c;
}
I have tried to implement it in all ways and error is same...here's an instance
Matrix x(m,n); //m and n are known
x = a+b; // a and b are also m by n matrices
I have debugged the code using breakpoints and here's the error...
The local matrix 'c' in operator function is destroyed before it is returned and hence what is assigned to x is a garbage pointer..
Please suggest me something...
You need to define a copy constructor for your class. The copy constructor will need to allocate memory for mat and make a copy of the data.
Without this, when you return c, a new object is constructed that has the same value of mat as c. When c subsequently goes out of scope, it deletes c.mat. As a result, the copy of c is left with a dangling pointer.
Having done this, you should also implement an assignment operator.
The value you returned is used to initialize a temporary, and this temporary is then copied into the result after the value you returned has been destroyed. This is normal behavior (unless the call is elided because of NRVO).
However, since your class has no explicitly defined copy constructor, the implicitly generated one will be invoked, and that will just copy a pointer (mat) to stuff that has been deallocated by the returned object's destructor.
This is a violation of the so-called Rule of Three, a programming best-practice saying that whenever your class explicitly defines a copy-constructor, an assignment operator, or a destructor, then it should define all of them. The rationale is that a class that defines one of them most likely does so because it is managing some resource, and for correctly handling resource releasing/acquiring logic, all of those three special member functions are needed.
Notice that in C++11 you can also have a move constructor that will be allowed to perform the transfer of the Matrix's content just by assigning pointers and invalidating the object you moved from.
Matrix(Matrix&& m)
{
mat = m.mat;
m.mat = nullptr;
}
Of course, if you introduce a move constructor, you will have to modify your class destructor accordingly to check if you really have to release the allocated memory:
~Matrix()
{
if (m.mat == nullptr)
{
return;
}
...
}
Your Matrix class has a raw pointer member and presumably allocates memory in its constructors, yet you have no copy constructor or copy assignment operator.
Also, you have a destructor, yet you have no copy constructor or copy assignment operator. This is a violation of the Rule of Three.
Your Matrix c is a local variable. So it is destroyed when that method where it was created ends. In C++ this unwanted situation is usually solved by copying objects. You can define copy constructor and assignment operator = with the same functionality. The problem of copying is that it is slow, so if you want it to be faster, you should use a different approach withotu copying. For example, you can add a parameter to the method where caller would pass a reference to the existing matrix object where to store the result.
You need a copy constructor and an assignment operator for your class that make a deep copy of the object as the compiler generated functions will not.
The compiler generated copy constructors and assignment operators will simply copy the objects contained in the class. In your case these are PODs, so the automatically generated functions will simply do a bitwise copy. In the case of the double**, this will result in the copy of the pointer value, not the pointed to values. As a result, you end up with two Matrix objects pointing to the same underlying data, just before the destructor pulls the rug out from underneath you.
You should change your code to return a Matrix *, rather than a Matrix object. This way you can ensure that the Matrix object lives after the function. (Your current code makes the Matrix object a function variable, thus it will be removed after the function has ended).
Your code could look like this:
Matrix *Matrix::operator+(const Matrix& other)
{
Matrix *c = new Matrix(m,n);
for(int i=0;i<m;i++)
{
for(int j = 0; j<n;j++)
c->mat[i][j] = mat[i][j] + other.mat[i][j];
}
return c;
}
EDIT: Apparently this is bad practice, guess I also learned something today :)

C++ operator destroys input variables

This is probably just me being stupid somehow or the other, but I am relatively new to C++, so forgive me the idiocy. I'm trying to teach myself how to use operators. I've defined a very basic operator as follows:
Matrix::Matrix operator+(Matrix a1, Matrix a2) {
if(a1.rows != a2.rows || a1.cols != a2.cols) {
std::cout << "ERROR: Attempting to add matrices of non-equal size." << std::endl;
exit(6);
}
int i, j;
Matrix c(a1.rows, a1.cols);
for(i = 0; i < a1.rows; i++)
for(j = 0; j < a1.cols; j++)
c.val[i][j] = a1.val[i][j] + a2.val[i][j];
return c;
}
The class Matrix represents a matrix, and has a constructor that takes two ints as input (the number of rows and columns in the matrix, respectively), and creates a 2D array of doubles of the appropriate size (named val). This function works as supposed to in that the value for c is correct, but it also appears to destruct a1 and a2. That is, if I write
Matrix c = a + b;
It gives the right result, but a and b are no longer usable, and I get a glibc error at the end of the code claiming I am trying to destruct a and b when they have already been destructed. Why is this?
Your signature is wrong:
Matrix operator+(Matrix a1, Matrix a2)
it should be
Matrix operator+(const Matrix& a1, const Matrix& a2)
The reason it appears to destroy a1 and a2 is because, well, it is, since those are temporary copies created in the method scope.
If the original values are destroyed, you're probably violating the rule of three. When a1 and a2 are destroyed, the destructor gets called, and you're probably deleting pointers in the destructor. But since the default copy constructor does only a shallow copy, the copied a2 and a1 will delete the original memory.
Edit: Since there are split opinions about this, I'll extend my answer:
Assume:
struct A
{
int* x;
A() { x = new int; *x = 1; }
~A() { delete x; }
};
//option 1:
A operator + (A a1, A a2)
{
A a; return a; //whatever, we don't care about the return value
}
//option 2:
A operator + (const A& a1, const A& a2)
{
A a; return a; //again, we don't really care about the return value
}
In this first example, the copy constructor is not implemented.
A copy constructor is generated by the compiler. This copy constructor copies x into the new instance. So if you have:
A a;
A b = a;
assert( a.x == b.x );
Important note that the pointers are the same.
Calling option 1 will create copies inside operator +, because the values are passed by value:
A a;
A b;
a + b;
//will call:
A operator + (A a1, A a2)
// a1.x == a.x
// a2.x == n.x
When operator + exits, it will call delete x on objects a1 and a2, which will delete the memory that is also pointed to by a.x and b.x. That is why you get the memory corruption.
Calling option 2 however, since no new objects are created because you pass by reference, the memory will not be deleted upon function return.
However, this isn't the cleanest way to solve the issue. It solves this issue, but the underlying one is much more important, as Konrad Pointed out, and I have in my original answer (although haven't given it enough importance, I admit).
Now, the correct way of solving this is properly following the rule of three. That is, have an implementation for destructor, copy constructor and assignment operator:
struct A
{
int* x;
A() { x = new int; *x = 1; }
A(const A& other) //copy constructor
{
x = new int; // this.x now points to a different memory location than other.x
*x = other.(*x); //copy the value though
}
A& operator = (const A& other) //assignment operator
{
delete x; //clear the previous memory
x = new int;
*x = other.(*x); //same as before
}
~A() { delete x; }
};
With this new code, let's re-run the problematic option 1 from before:
A a;
A b;
a + b;
//will call:
A operator + (A a1, A a2)
// a1.x != a.x
// a2.x != n.x
Because the copies a1 and a2 now point to different memory locations, when they are destroyed, the original memory is intact and the original objects - a and b remain valid.
Phew! Hope this clears things up.
I’m assuming that you are allocating dynamic memory inside the Matrix class using new and didn’t implement a custom copy constructor, thus violating the rule of three.
The cause of the error would then be that the local copy of the Matrix instances reuses the dynamic memory of the argument instances, and their destructors free it at the end of the method.
The solution is very simple: Don’t use pointers. Instead, you could use a nested std::vector to store the data.
Furthermore, the head of the operator is mangled. Depending on where you declare the function, it must either look like this, if you define the operator inside the class:
ReturnType operator +(Arg1)
Or, if you define it outside the class, it needs to look like this:
ReturnType operator +(Arg1, Arg2)
Yours is a wild mix of both. I’m assuming that your operator definition should look as follows:
Matrix operator +(Matrix a, Matrix b) { … }
If your code compiles then this is either an error in the compiler or you are using a very weird class structure indeed. Furthermore, as Luchian pointed out, it’s more efficient to pass the arguments as const& rather than by value. However, you should first make your code run correctly.
As Luchian Grigore pointed out, your signature is wrong and should be:
Matrix operator+(const Matrix& a1, const Matrix& a2)
But even this signature should not itself spoil a and b. But because you are copying arguments, I have another suspicion.
Have you defined your own copy constructor? I think you may be deleting the old variables when you are copying their values to the operator's arguments.
Please share your copy constructor (and preferably also operator= and the two-argument constructor that you use in this operator)
Since the size of the matrix is given at runtime, I suppose that the Matrix class hold a pointer that is initialized with a dynamically allocated array that is deleted by the destructor.
In that case, the copy constructor and the assignment operator must also be definedin order to allocate the copies of what the a matrix holds.
Not doing that, the default copy and assignment will just reassign the pointers, letting you with two or more Matrix holding a same array. And when one is destroyed (thus deleting the array) the others remain dangling.

Matrix class operator overloading,destructor problem

I was trying to write a matrix class which would be able to find inverse,adjoint,etc. of a square matrix of any order.
The constructor initializes an identity matrix of order n(passed to it).
class Matrix
{
int** elements;
int order;
public:
Matrix& operator=(const Matrix& second_inp)
{
if(this->order!=second_inp.order)
cout<<"The matrix cannot be assigned!!!\n"<<this->order<<"\n"<<second_inp.order;
else
{
for(int i=0;i<this->order;i++)
for(int j=0;j<this->order;j++)
this->elements[i][j] = second_inp.elements[i][j];
}
return *this;
}
Matrix operator*(const Matrix& a)const
{
Matrix c(a.order);
for(int i=0;i<c.order;i++)
for(int j=0;j<c.order;j++)
c.elements[i][j]=0;
if (this->order!=a.order)
{
cout<<"The 2 Matrices cannot be multiplied!!!\n";
return Matrix();
}
else
{
for(int i=0;i<a.order;i++)
for(int j=0;j<a.order;j++)
for(int k=0;k<a.order;k++)
c.elements[i][j] += (this->elements[i][k])*(a.elements[k][j]);
return c;
}
}
};
~Matrix()
{
for(int i=0;i<this->order;i++)
delete[] *(elements+i);
delete[] elements;
elements=nullptr;
}
If i were to run the following code using this class:
Matrix exp1(2),exp2(2),exp3(2);
exp1.get_matrix();
exp3=exp1*exp2;
exp3.show_matrix();
I get a run-time error, while debugging i found out that, after the multiplication(exp1*exp2) the =operator was not able to access the data if the result of the *operator.
But if i were to use a manual destructor like this one at the end of the main() to free all allocated memory, the program works fine.
void destroctor()
{
for(int i=0;i<order;i++)
delete[] *(elements+i);
delete[] elements;
}
how can i edit the destructor or the operator overloads to correct this problem?
The constructor i used:
Matrix(int inp_order):order(inp_order)
{
elements=new int*[order];
for(int i=0;i<order;i++)
*(elements+i)=new int[order];
for(int i=0;i<order;i++)
for(int j=0;j<order;j++)
{
if (i==j)
*(*(elements+j)+i)=1;
else
*(*(elements+j)+i)=0;
}
}
It is hard to tell what is going wrong, since you have not posted your constructors.
In the exp3=exp1*exp2; a lot of things happen:
First a new matrix c is constructed in the operator* function. Then the return c; statement calls the copy constructor and then the destructor. After that operator= is called and after that the destructor for the temporary matrix again.
I think what happens is that you are using the default copy constructor which does not make a deep copy. That way the destructor being called at the time of return c deletes the data that still shared between the matrices.
I get a run-time error, while debugging i found out that, after the multiplication(exp1*exp2) the =operator was not able to access the data if the result of the *operator.
You didn't show us your constructor, so there is no way to tell why you are getting this errors.
I suspect that the cause is that you aren't allocating the memory needed to contain your matrix. You declared it as an int**, so you need to allocate an array of int* pointers, and for each of those you need to allocate an array of int.
Edit
While I was typing this you posted code for your constructor.
You are not returning a value from your overload of operator*, and you don't have a copy constructor (rule of three).
Do you have compiler warnings enabled? Any compiler worth its salt would have complained about the missing return statement in the operator overload.
You have not defined a copy constructor, so the compiler will generate one for you. This constructor will be called in order to copy the return value of operator*(const & Matrix a) into the result.
As the generated copy constructor only performs a shallow memberwise copy, it will not allocate a new array of elements, hence the error.