123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180 |
- #ifndef CPPDB_REF_PTR_H
- #define CPPDB_REF_PTR_H
- #include <cppdb/errors.h>
- #include <atomic>
- namespace cppdb {
-
-
-
-
-
-
-
-
-
-
-
-
- template<typename T>
- class ref_ptr {
- public:
-
-
-
- ref_ptr(T *v=0) : p(0)
- {
- reset(v);
- }
-
-
-
- ~ref_ptr()
- {
- reset();
- }
-
-
-
- ref_ptr(ref_ptr const &other) : p(0)
- {
- reset(other.p);
- }
-
-
-
- ref_ptr const &operator=(ref_ptr const &other)
- {
- reset(other.p);
- return *this;
- }
-
- #ifdef __BORLANDC__
- ref_ptr const &operator=(T *other)
- {
- reset(other);
- return *this;
- }
- #endif
-
-
-
- T *get() const
- {
- return p;
- }
-
-
-
- operator bool() const
- {
- return p!=0;
- }
-
-
-
- T *operator->() const
- {
- if(!p)
- throw cppdb_error("cppdb::ref_ptr: attempt to access an empty object");
- return p;
- }
-
-
-
- T &operator*() const
- {
- if(!p)
- throw cppdb_error("cppdb::ref_ptr: attempt to access an empty object");
- return *p;
- }
-
-
-
- void reset(T *v=0)
- {
- if(v==p)
- return;
- if(p) {
- if(p->del_ref() == 0) {
- T::dispose(p);
- }
- p=0;
- }
- if(v) {
- v->add_ref();
- }
- p=v;
- }
- private:
- T *p;
- };
-
-
-
- class ref_counted {
- public:
-
-
-
- ref_counted() : count_(0)
- {
- }
-
-
-
- virtual ~ref_counted()
- {
- }
-
-
-
- long add_ref()
- {
- return ++count_;
- }
-
-
-
- long use_count() const
- {
- long val = count_;
- return val;
- }
-
-
-
- long del_ref()
- {
- return --count_;
- }
-
-
-
- static void dispose(ref_counted *p)
- {
- delete p;
- }
- private:
- std::atomic<long> count_;
- };
- }
- #endif
|