Returning references while using shared_ptrs
- by Goose Bumper
Suppose I have a rather large class Matrix, and I've overloaded operator== to check for equality like so:
bool operator==(Matrix &a, Matrix &b);
Of course I'm passing the Matrix objects by reference because they are so large.
Now i have a method Matrix::inverse() that returns a new Matrix object. Now I want to use the inverse directly in a comparison, like so:
if (a.inverse()==b) { ... }`
The problem is, this means the inverse method needs to return a reference to a Matrix object. Two questions:
Since I'm just using that reference in this once comparison, is this a memory leak?
What happens if the object-to-be-returned in the inverse() method belongs to a boost::shared_ptr? As soon as the method exits, the shared_ptr is destroyed and the object is no longer valid. Is there a way to return a reference to an object that belongs to a shared_ptr?