Skip to content

Instantly share code, notes, and snippets.

@sumerman
Created December 4, 2010 12:22
Show Gist options
  • Save sumerman/728142 to your computer and use it in GitHub Desktop.
Save sumerman/728142 to your computer and use it in GitHub Desktop.
Simple non-intrusive refc-smart-pointer
/*
* shared_ptr.h
*
* Created by Valeryi Meleshkin.
*
*/
#ifndef __SHARED_PTR__
#define __SHARED_PTR__
class shared_ptr_counter {
protected:
int *rfc_;
shared_ptr_counter(const shared_ptr_counter &spc): rfc_(spc.rfc_) {}
shared_ptr_counter(): rfc_(0) {}
};
template <typename T>
class shared_ptr: public shared_ptr_counter {
T *ptr_;
protected:
void retain() {
++(*rfc_);
}
void release() {
--(*rfc_);
if (*rfc_ == 0) {
delete ptr_;
delete rfc_;
ptr_ = 0;
rfc_ = 0;
}
}
public:
explicit shared_ptr(T *ptr) {
ptr_ = ptr;
rfc_ = new int;
(*rfc_) = 1;
}
explicit shared_ptr() {
ptr_ = new T();
rfc_ = new int;
(*rfc_) = 1;
}
~shared_ptr() {
release();
}
operator T* () {
return ptr_;
}
operator const T* () const {
return ptr_;
}
/*
operator void* () {
return ptr_;
}
*/
template <typename T2>
shared_ptr(shared_ptr<T2> &sp): shared_ptr_counter(sp), ptr_(static_cast<T2 *>(sp)) {
retain();
}
shared_ptr(const shared_ptr<T> &sp): shared_ptr_counter(sp), ptr_(sp.ptr_) {
retain();
}
shared_ptr<T> &operator = (const shared_ptr<T> &sp) {
release();
ptr_ = sp.ptr_;
rfc_ = sp.rfc_;
retain();
return *this;
}
T& operator * () const {
return *ptr_;
}
T* operator -> () const {
return ptr_;
}
};
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment