Skip to content

Instantly share code, notes, and snippets.

@Indy9000
Created October 1, 2019 12:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Indy9000/6817e1d0e2b1a88b92b64ab00647f170 to your computer and use it in GitHub Desktop.
Save Indy9000/6817e1d0e2b1a88b92b64ab00647f170 to your computer and use it in GitHub Desktop.
Implementing a simple shared_ptr class
// In C++11 we got shared pointer. The standard implementation is much more complete and robust,
// but here I show a barebones version of it to illustrate the main components.
// Behaviour: SharedPTR manages the lifetime of a pointer to a templated object
// SharedPTR can be used to share the pointed object among other SharedPTRs.
// When all of them have given up the pointed object, The SharedPTR deallocates the
// pointed object
// For this we use reference counting. And the main point is that the counter should be a shared object itself
// that would be shared among the SharedPTRs.
template<typename T>
struct SharedPTR{
T* ptr = nullptr;
// manages the life time count
struct Counter{
int counter = 0;
int inc(){ return counter++;}
int dec(){ return counter--;}
bool isZero(){ return counter == 0;}
};
Counter * C = new Counter();
explicit SharedPTR(){} // explicit default constructor
explicit SharedPTR(T* t):ptr(t){ C->inc(); } // explicit parameterised default constructor
// copy constructor
SharedPTR(const SharedPTR<T>& other){
if (this!=&other){ // avoid copying self
C = other.C;
ptr = other.ptr;
C->inc();
}
}
// copy assignment operator
SharedPTR<T>& operator=(const SharedPTR<T>& other){
if (this!=&other){ // avoid copying self
C = other.C;
ptr = other.ptr;
C->inc();
}
return *this;
}
~SharedPTR(){
C->dec();
if(C->isZero()){
delete ptr;
delete C;
}
}
};
struct dummy{
dummy(){ std::cout << "constructed\n"; }
~dummy(){ std::cout << "destructed\n"; }
};
int main(){
SharedPTR<dummy> p1;
{
SharedPTR<dummy> sp(new dummy());
p1 = sp;
}
std::cout << "here\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment