2

i have this class

class Matrix
{
    int size;

    std::unique_ptr<std::unique_ptr<int[]>[]>  val;

public:

    Matrix(int size1)
    {
        size=size1;
        val=std::make_unique< std::unique_ptr<int[]>[] >(size);

        ...
    }

... move constructor,move assignment operator

    Matrix& operator+(Matrix &m)
    {
        Matrix sumMatrix(size);
        for ( int i = 0; i < size; ++i)
        {
            for (int j = 0; j < size; ++j){
                sumMatrix.val[i][j]=this->val[i][j]+m.val[i][j];
            }

        }
        return sumMatrix;
    }

and main :

...
Matrix e=b+c;
    std::cout<<"e="<<std::endl;
    e.print();

and i have this error :

warning: reference to local variable 'sumMatrix' returned [-Wreturn-local-addr] Matrix sumMatrix(size);

Can someone please help me with this ??

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
Ac1234
  • 67
  • 6
  • Should probably read this: [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading), in particular, the section on arithmetic operations. – WhozCraig May 10 '20 at 21:30
  • `Matrix& operator+(Matrix &m);` should be `Matrix operator+(const Matrix &m) const;` Also, you may need to check the size of `m` too. It's risky to just assume they are the same size. You could make the size a template parameter. – Ted Lyngmo May 10 '20 at 21:32

1 Answers1

5

Return by value, as you should for operator+ most of the time:

//   vvv--Removed &     vvvvv-----vvvvv--Const is more appropriate here
Matrix operator+(Matrix const &m) const { ... }

This will require a copy constructor, make sure to add that. Also note that you should probably collect your for-loop logic into an operator+= and simplify operator+ significantly while providing more functionality for the end-user:

Matrix& operator+=(Matrix const& m) {
  for (int i = 0; i < size; ++i) {
    for (int j = 0; j < size; ++j) {
      //vvv--No need for this-> in C++    
      val[i][j] += m.val[i][j];
    }
  }
  return *this;
}

Matrix operator+(Matrix const& m) const {
  Matrix sumMatrix{m}; // requires a copy constructor.
  sumMatrix += *this;
  return sumMatrix;
}
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93