开发者

Question regarding object lifetime and deallocation responsibility

开发者 https://www.devze.com 2023-02-08 15:35 出处:网络
I\'m sitting here with the following class: class TagCompound : public Tag { public: // [...] Constructor and other methods

I'm sitting here with the following class:

class TagCompound : public Tag
{
   public:
      // [...] Constructor and other methods
      void insert(Tag *t);
      // [...] more modifying methods

   protected:
      std::vector<Tag *> _values;
};

TagCompound::insert(Tag *t)
{
   _values.push_back(t);
}

This is all fun and dandy and works with both stack and heap allocated objects of a class derived of Tag.

Of course, if the pointer supplied to TagCompound::insert() is allocated on the heap, it has to be deallocated somewhere outside. This means that every method that removes something from the vector has to return the removed pointer so the outside can free it again, if it has to.

I don't like this, it's messy and error prone if the caller forgets to delete it.

The other thing I tried out was simply assuming every pointer in t开发者_开发百科he vector _values would be heap allocated and do the deletion in every function that somehow removed something from _values and have delete run on every remaining element in TagCompound::~TagCompound.

That of course completely ruled out stack pointers by causing an invalid deletion.

I also tried using std::auto_ptr but soon I found out that it doesn't work with STL containers. There's probably something from boost, but I don't want to use boost (or any kind of third party library).

Was I already on the right way with one of these methods, or is there some kind of black magic that works even better?


You can use tr1::shared_ptr (or std::shared_ptr if you have a 0x compiler) with custom deleters for statically allocated objects (no-op deleters in this case).


One solution is to require the objects to be dynamically allocated, with lifetimes managed by shared_ptr<Tag>.

You can use boost::shared_ptr from the Boost library (there's also a std::shared_ptr in upcoming c++0x standard).

Then you have a vector of shared_ptrs and just let those shared_ptr manage life times automatically. A Tag object will then be destroyed automatically when the last shared_ptr reference to it disappears. And not before.

Cheers & hth.,

0

精彩评论

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

关注公众号