Using const references as local smart pointer?

C

Chris Thomasson

I am fine-tuning some last minute things in my c++ allocator lib and was
thinking of ways to manage local references to system objects created with
factory functions. I started to tinker around with using const references to
represent a smart-pointer template that uses intrusive reference counting.
Anyway, here is a short little program that should clearly demonstrate what
I am messing around with:

_________________________
#include <cstdio>
#include <exception>


template<typename T>
class AutoRef {
mutable T *m_State;

public:
AutoRef(T* const State) throw() : m_State(State) {
printf("(%p)AutoRef::AutoRef(%p)\n", (void*)this, (void*)State);
}

~AutoRef() throw() {
T::RefCount_XAdd(m_State, -1);
printf("(%p)AutoRef::~AutoRef\n", (void*)this);
}

public:
AutoRef(AutoRef const&);
AutoRef const& operator =(AutoRef const&);

public:
void Cancel() const throw() {
m_State = 0;
printf("(%p)AutoRef::Cancel()\n", (void*)this);
}

public:
T* operator ->() const {
if (! m_State) { throw std::exception(); }
return m_State;
}

T& operator *() const {
if (! m_State) { throw std::exception(); }
return *m_State;
}
};


class Foo {
typedef AutoRef<Foo> AutoRef_t;

private:
int m_RefCount;

public:
typedef AutoRef_t const &Handle;

static AutoRef_t Create() {
Foo* const This = new Foo;
printf("(%p)Foo::Create()\n", (void*)This);
return AutoRef_t(This);
}

private:
static void Destroy(Foo* const This) {
delete This;
printf("(%p)Foo::Destroy()\n", (void*)This);
}

public:
Foo() : m_RefCount(1) {
printf("(%p)Foo::Foo()\n", (void*)this);
}

~Foo() throw() {
printf("(%p)Foo::~Foo()\n", (void*)this);
}

public:
static void RefCount_XAdd(Foo* const This, int Count) {
if (This) {
--This->m_RefCount;
printf("(%p)Foo::RefCount_XAdd(%d)\n", (void*)This, Count);
if (This->m_RefCount < 1) {
Destroy(This);
}
}
}

public:
void Test(int State) {
printf("(%p)Foo::Test(%d)\n", (void*)this, State);
}
};


int main() {
{
Foo::Handle Foo1 = Foo::Create();
Foo1->Test(1);

Foo::Handle Foo2 = Foo1;
Foo2->Test(2);

{
Foo::Handle Foo3 = Foo1;
Foo::Handle Foo4 = Foo2;
Foo3->Test(3);
Foo4->Test(4);
}

Foo1->Test(5);
Foo2->Test(6);
}

printf("\n\n____________________\npress <ENTER> to exit...\n");
getchar();
return 0;
}

----------


Is this legitimate? Or, is the idea basically equal to a pile of pointless
crap!


Any thoughts?

:^)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top