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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With