From 79ee50a1cf4415e214298bf696aa3fc44e308d02 Mon Sep 17 00:00:00 2001 From: Mike Buland Date: Tue, 10 Apr 2007 13:43:05 +0000 Subject: David had it half right...to make it work like something that's actually a const pointer he's right, the pointer needs to be rebindable, but for a: const int *p; p can be changed, but not what p points to. I've added the rest of the operators in sptr that should accomplish this, and a test that actually tests the correctness of SPtr used this way against a normal pointer, both tests check out 100%, hopefully this dosen't break anything, but if it should act like a pointer, this is how to do it. (I totally forgot that const pointers were rebindable). --- src/sptr.h | 14 ++++++++++++-- src/tests/constsptr2.cpp | 30 ++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 src/tests/constsptr2.cpp (limited to 'src') diff --git a/src/sptr.h b/src/sptr.h index 9a6a2d6..3304501 100644 --- a/src/sptr.h +++ b/src/sptr.h @@ -45,16 +45,26 @@ public: return *pRefCnt; } - T *operator->() const + const T *operator->() const { return pData; } - T *operator*() const + const T &operator*() const + { + return *pData; + } + + T *operator->() { return pData; } + T &operator*() + { + return *pData; + } + SPtr operator=( const SPtr &src ) { decCount(); diff --git a/src/tests/constsptr2.cpp b/src/tests/constsptr2.cpp new file mode 100644 index 0000000..8ccb20c --- /dev/null +++ b/src/tests/constsptr2.cpp @@ -0,0 +1,30 @@ +#include "sptr.h" + +void nonsptr() +{ + int a = 5; + int b = 10; + const int *p = &a; + p = &b; + printf("p = %d\n", (*p) ); + //(*p)++; +} + +void sptr() +{ + int a = 5; + int b = 10; + const SPtr p = new int(a); + p = new int(b); + printf("p = %d\n", (*p) ); + //(*p)++; +} + +int main() +{ + printf("Non-sptr:\n"); + nonsptr(); + printf("sptr:\n"); + sptr(); +} + -- cgit v1.2.3