Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning address or local variable or temporary C++ warning [duplicate]

Tags:

c++

warnings

Possible Duplicate:
c++ warning: address of local variable

Hi, When i write this code:

//Returns the transpose matrix of this one
SparseMatrix& SparseMatrix::transpose()const{
    vector<Element> result;
    size_t i;
    for(i=0;i<_matrix.size();++i){
        result.push_back(Element(_matrix.at(i)._col, _matrix.at(i)._row, _matrix.at(i)._val));
    }

    return SparseMatrix(numCol,numRow,result);
}

I get the warning "returning address or local variable or temporary". The last line calls the SparseMatrix constructor. I don't understand what's wrong with this code, and how can i fix it so i can return a SparseMatrix object as i want.

like image 253
limlim Avatar asked Oct 06 '10 08:10

limlim


2 Answers

You're returning a reference, not an actual object - note the & here:

SparseMatrix& SparseMatrix::transpose()const{

If you want to return the actual object, remove that &.

The last line does indeed call the constructor, but it doesn't return the resulting object. That object immediately gets destroyed, and an invalid reference to it gets returned.

like image 139
RichieHindle Avatar answered Nov 09 '22 19:11

RichieHindle


In C++, local variables are 'automatically' destructed when going out of scope. Your return statement will create a nameless, temporary variable of type SparseMatrix that will immediately go out of scope. Hence, returning a reference to it doesn't make sense.

It may be easier to return by value: then a copy of the temporary will be returned. The compiler can optimize that away (copy elision).

If you really want to pass an object out of a function, you should create it on the heap, using new:

SparseMatrix* SparseMartix::transopse()const{


     //...
     return new SparseMatrix(...);

}

But then, you need to take care of the lifetime of the returned object yourself.

like image 37
xtofl Avatar answered Nov 09 '22 19:11

xtofl