Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
C++
How can I improve this code?
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="Tom Smith, post: 2582387"] I'm writing my own smart pointer class (as an exercise, not for real life use); I've got it to a point where I think it's usable: but I'm not quite sure. Any comments on the class gratefully received. Cheers - Tom /** code starts here **/ /** **/ /** obviously ! **/ #include <map> template <class T> class ptr { public: inline ptr() : t(null_t) { }; inline ptr(ptr<T> const& other) : t (other.t) { Count[t]++; } inline ptr(T* const t2) : t (t2) { Count[t]++; } inline ~ptr() { Count[t]--; if (Count[t]==0 && t != null_t) delete t; } ptr<T> operator= (T* const t2) { Count[t]--; if (Count[t]==0 && t != null_t) delete t; Count.erase(t); t = t2; Count[t]++; } ptr<T> operator= (ptr<T> const& other) { Count[t]--; if (Count[t]==0 && t != null_t) delete t; Count.erase(t); t = other.t; Count[t]++; } bool operator== (ptr<T> const& other) { return (t == other.t); } bool operator== (T* const t2) { return (t == t2); } T* operator-> () { return t; } operator T* () { return t; } T* operator() (){ return t; } private: T* t; static std::map<T*, int> Count; static T* const null_t; }; template <class T> std::map<T*, int> ptr<T>::Count; template <class T> T* const ptr<T>::null_t = 0; [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
C++
How can I improve this code?
Top