开发者

Deletion of data possibly held in two different places

I have a program doing something like the following:

class SomeObject{}
{
    void function(int x, int y);
    void function(SomeOtherObject *z);

    SomeOtherObject *ptrToObj;
}

SomeObject::function(int x, int y)
{
    ptrToObj = new SomeOtherObject(x, y);
}

SomeObject::function(SomeOtherObject *z)
{
    ptrToObj = z;
}

My problem is that I don't know the best way to handle deleting that new object when I want to get rid of or initialize an instance of SomeObject, since I can't count on it actually having been made by SomeObject. (a manager is handling the deletion if SomeObject is passed a pointer)

Options I thought of:

  • Copy object and point to that. (It seems messy to have two copies, though the object isn't that large)
  • Make a boolean that is set if the object needs to be deleted. (this is just sort of weird and hacky)
  • Make another pointer to hold the object created by SomeObject, point ptrToObj to that pointer instead when it is assigned. (so basically, you know the second pointer can safely be deleted if it isn't NULL)
  • Implement a ref-count开发者_如何学Cing pointer. (this is a little more than I wanted to get into for this)

I did the third one, but I know there must be a better way to handle this problem!


Use a shared_ptr, either the one from Boost or the one in a recent C++(0x) library. shared_ptr does reference counting for you.


This case might be solved by shared_ptr, as answered before, but I recommend reading about smart pointers for others strategies. I found an interesting summary on the techniques and which cases to use them.


If you don't want to use smart pointers look at observer DP.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜