From 531761d77331915b3e6495d10e03191ba10c04d2 Mon Sep 17 00:00:00 2001 From: David Date: Tue, 10 Apr 2007 00:26:26 +0000 Subject: david - wow... that seems a little kludgy... see the constsptr test for details, but basically i had to make the members of sptr mutable to get this to work the way it seems it should... maybe i'm missing something... --- src/sptr.h | 20 ++++++++--- src/tests/constsptr.cpp | 94 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 109 insertions(+), 5 deletions(-) create mode 100644 src/tests/constsptr.cpp diff --git a/src/sptr.h b/src/sptr.h index 0ea8bca..9a6a2d6 100644 --- a/src/sptr.h +++ b/src/sptr.h @@ -40,7 +40,7 @@ public: (*pRefCnt) = 1; } - int32_t count() + int32_t count() const { return *pRefCnt; } @@ -65,7 +65,17 @@ public: return *this; } - bool operator==( const SPtr &src ) + const SPtr operator=( const SPtr &src ) const + { + decCount(); + pRefCnt = src.pRefCnt; + pData = src.pData; + (*pRefCnt) += 1; + + return *this; + } + + bool operator==( const SPtr &src ) const { return pData == src.pData; } @@ -81,7 +91,7 @@ public: } private: - void decCount() + void decCount() const { if( pRefCnt ) { @@ -97,8 +107,8 @@ private: } } - int32_t *pRefCnt; - T *pData; + mutable int32_t *pRefCnt; + mutable T *pData; }; template< typename Tb, typename Ta > SPtr SPtrCast( SPtr src ) diff --git a/src/tests/constsptr.cpp b/src/tests/constsptr.cpp new file mode 100644 index 0000000..e6f87c7 --- /dev/null +++ b/src/tests/constsptr.cpp @@ -0,0 +1,94 @@ +#include +#include "sptr.h" + +template +class DataBase +{ +public: + DataBase(): + _bHas(false) + { + } + + virtual ~DataBase() + { + clr(); + } + + virtual bool has() const + { + return _bHas; + } + + virtual void clr() + { + _bHas = false; + } + + virtual void set(T d) + { + _tVal = d; + _bHas = true; + } + + virtual T const &get() const + { + if(!has()) + throw "no data"; + return _tVal; + } + + virtual T &get() + { + if(!has()) + throw "no data"; + return _tVal; + } + +protected: + bool _bHas; + T _tVal; +}; + + +class Test +{ +public: + Test(){}; + virtual ~Test(){}; + + void set(int i) + { + _i = i; + } + + int get() const + { + return _i; + } + +private: + int _i; +}; + +int main() +{ + typedef SPtr TestPtr; + + TestPtr t1(new Test); + t1->set(42); + + printf("t1: %d.\n", t1->get()); + + const TestPtr t2 = t1; + + printf("t2: %d.\n", t2->get()); + + typedef DataBase DBTP; + + DBTP db; + db.set(t1); + + printf("dbt1: %d.\n", db.get()->get()); +} + -- cgit v1.2.3