Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 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";
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement