Returning references while using shared_ptrs
Posted
by Goose Bumper
on Stack Overflow
See other posts from Stack Overflow
or by Goose Bumper
Published on 2010-04-25T04:18:31Z
Indexed on
2010/04/25
4:23 UTC
Read the original article
Hit count: 286
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?
© Stack Overflow or respective owner