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.
Reference countable objects?
I''d like to use reference counts in my objects (similar to DirectX interfaces have). How?
I think I should have one base class:
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.
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.
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:
// Here''s simple example how to use it:
I just put this here if someone wants to learn from this
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
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement