开发者

How to delete pointer only once?

开发者 https://www.devze.com 2023-02-10 07:45 出处:网络
enum Reaction{single,chain}; class X { X* parent_; X* left_; X* right_; Reaction* reaction_;//this pointer p开发者_如何学运维oints from every obj to the same place, cannot be static
enum Reaction{single,chain};

class X
{
X* parent_;
X* left_;
X* right_;
Reaction* reaction_;//this pointer p开发者_如何学运维oints from every obj to the same place, cannot be static
};

The Q is: how to design destructor in order to delete reaction_ only once?


Three immediate ideas:

1) Must reaction_ be owned by an instance of class X? Can't it be owned by an external entity, so that no X::~X will ever need to delete it?

2) Use boost::shared_ptr

3) Implement your own reference counting using a static int. Remember locking if you're multithreaded.


What is problem with this:

~X()
{
   delete reaction_;
}

Or, maybe I didn't understand your question completely!


Use boost::shared_ptr<Reaction> in your objects


Use a boost::shared_ptr or a std::shared_ptr (c++0x). It will count references and call delete when needed only.

0

精彩评论

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