开发者

Returning references while using shared_ptrs

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 wan开发者_Go百科t 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:

  1. Since I'm just using that reference in this once comparison, is this a memory leak?

  2. 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜