You do not need to return a reference from the inverse()
method. Return the object itself. The compiler will create a temporary reference for passing to the equality operator, and that reference will go out of scope immediately after the operator returns.
To answer your question whether or not it's a memory leak.
Depends on where you're going to get that object that you're going to return from inverse()
. If you're returning a reference to an object allocated on the heap, like so:
Matrix& inverse()
{
Matrix* m = new Matrix();
return *m;
}
then that's definitely a leak. Indeed, you're never going to free that memory, are you?
If you're returning a reference to a stack-allocated object, like so:
Matrix& inverse()
{
Matrix m;
return m;
}
then I wouldn't say it's a leak... Instead, it's a crash. A General Protection Fault, if you will. Or a memory corruption. Or something else out of a nightmare. Don't do this. Ever.
A stack-allocated object like that goes out of scope when the function returns, and that memory is reclaimed. But what's worse, it's reclaimed for the purposes of calling other functions, and allocating those functions' local variables. Therefore, if you retain a reference to a stack-allocated object, then you're pretty much screwed.
And finally, you might use some kind of custom storage for that Matrix, like so:
static Matrix _inversed;
Matrix& inverse()
{
_inversed = ...
return _inversed;
}
Technically, this wouldn't constitute a leak or a crash. But you really don't want to do it either, because it's not clear from the signature of the inverse()
method that it actually returns a reference to shared instance, which will make it all too easy to forget this, and to fiddle with those "inversed" matrices, screwing up your data.