From e19acafd485a1c6a027bc967945d914fa5ed38b9 Mon Sep 17 00:00:00 2001 From: Mike Buland Date: Fri, 24 Nov 2006 10:40:34 +0000 Subject: Added a simple smart-pointer. It deletes what's in it automatically and does ref-counting. You just have to be careful to not hand it an array... --- src/sptr.cpp | 1 + src/sptr.h | 85 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/tests/sptr.cpp | 55 +++++++++++++++++++++++++++++++++++ 3 files changed, 141 insertions(+) create mode 100644 src/sptr.cpp create mode 100644 src/sptr.h create mode 100644 src/tests/sptr.cpp (limited to 'src') diff --git a/src/sptr.cpp b/src/sptr.cpp new file mode 100644 index 0000000..7f5e894 --- /dev/null +++ b/src/sptr.cpp @@ -0,0 +1 @@ +#include "sptr.h" diff --git a/src/sptr.h b/src/sptr.h new file mode 100644 index 0000000..c711a89 --- /dev/null +++ b/src/sptr.h @@ -0,0 +1,85 @@ +#ifndef SPTR_H +#define SPTR_H + +#include +#include + +template +class SPtr +{ +public: + SPtr() : + pRefCnt( NULL ), + pData( NULL ) + { + } + + ~SPtr() + { + decCount(); + } + + SPtr( SPtr &src ) : + pRefCnt( src.pRefCnt ), + pData( src.pData ) + { + (*pRefCnt) += 1; + } + + SPtr( T *pSrc ) : + pRefCnt( NULL ), + pData( pSrc ) + { + pRefCnt = new uint32_t; + (*pRefCnt) = 1; + } + + uint32_t count() + { + return *pRefCnt; + } + + T *operator->() const + { + return pData; + } + + T *operator*() const + { + return pData; + } + + SPtr operator=( const SPtr &src ) + { + decCount(); + pRefCnt = src.pRefCnt; + pData = src.pData; + (*pRefCnt) += 1; + } + + bool operator==( const SPtr &src ) + { + return pData == src.pData; + } + +private: + void decCount() + { + if( pRefCnt ) + { + (*pRefCnt) -= 1; + if( (*pRefCnt) == 0 ) + { + delete pRefCnt; + delete pData; + pRefCnt = NULL; + pData = NULL; + } + } + } + + uint32_t *pRefCnt; + T *pData; +}; + +#endif diff --git a/src/tests/sptr.cpp b/src/tests/sptr.cpp new file mode 100644 index 0000000..38d3675 --- /dev/null +++ b/src/tests/sptr.cpp @@ -0,0 +1,55 @@ +#include +#include "sptr.h" + +class Annoy +{ +public: + Annoy() : nCnt( 0 ) + { + printf("Created.\n"); + } + + ~Annoy() + { + printf("Destroyed.\n"); + } + + void go() + { + printf("%d: I'm annoying.\n", ++nCnt); + } + + int nCnt; +}; + +void beAnnoying( SPtr bob ) +{ + printf("bob-Count: %d\n", bob.count() ); + bob->go(); +} + +int main() +{ + SPtr pt( new Annoy ); + printf("Count: %d\n", pt.count() ); + pt->go(); + + { + SPtr pt2 = pt; + printf("Count: %d\n", pt2.count() ); + + pt2->go(); + + { + SPtr pt3( pt2 ); + printf("Count: %d\n", pt3.count() ); + + pt3->go(); + + beAnnoying( pt3 ); + } + printf("Count: %d\n", pt.count() ); + } + printf("Count: %d\n", pt.count() ); +} + -- cgit v1.2.3