Reference countable objects?

Started by
5 comments, last by stefu 22 years, 8 months ago
I''d like to use reference counts in my objects (similar to DirectX interfaces have). How? I think I should have one base class:
  
class ref
{
    int ref_count;
public:
    int AddRef() 
    { 
        ref_count++ 
    };
    int Release() 
    {
        if( --ref_count==0 ) delete this;
    }

protected:
    virtual ~ref() {};
};
  
I just thought of the Release() method. It should be able to delete the object itself? Is "delete this" allowed? It compiles well. I just want to be sure what I''m doing before I add include this to my code.
Advertisement
"delete this" is allowed.
Yeah, it''s allowed, but a bit dangerous in maintenance terms cos if any code in a member function operates on a member variable after ''delete this'' has executed, it''s gonna crash. It''s usually best to implement reference counting through a reference counted pointer, which tends to get around this by only destroying the object when all the pointers to it are gone.
"It''s usually best to implement reference counting through a reference counted pointer"

Could you shortly explain what does this mean? just a brief description.
Basically, you access the objects through another class which acts like a pointer, except it stores the reference count itself and deletes the object it points to when all instances of that pointer class that point to the object have gone. These pointers, when you assign one to another, will increase the reference count themselves, and presumably share it. (Through a pointer to int or something like that.)

Take a look at http://www.geocities.com/botstein/refcnt.html. Not a great example, but maybe you can get the idea.
That was great. I just don''t need that complicated ref counting. I wrote a simple for my use:

  template<class X> class ref_count{	int m_count;	X *m_ptr;public:	ref_count(X *ptr) : m_ptr(ptr), m_count(1) {};	~ref_count() { if( m_ptr ) delete m_ptr; }	int add_ref() 	{			return ++m_count; 	}	int del_ref() 	{		if( --m_count==0 ) 		{			delete m_ptr;			m_ptr = 0;		}		return m_count;	}	X* operator-> ( )	{ 		return m_ptr; 	}};  


// Here''s simple example how to use it:

  class test{public:	int i;	test() : i(0) {};};void run_test(){	ref_count<test> t( new test() );	// now ref count is 1	t->i = 10;	t.add_ref();	t.del_ref();	t.del_ref(); 	// now ref count is 0}  



I just put this here if someone wants to learn from this
Wow! Shades of COM programming. Look at ATL sometime.

This topic is closed to new replies.

Advertisement