Skip to content

Instantly share code, notes, and snippets.

@cyndibaby905
Last active November 27, 2015 07:48
Show Gist options
  • Save cyndibaby905/7411fd50e04146ab9558 to your computer and use it in GitHub Desktop.
Save cyndibaby905/7411fd50e04146ab9558 to your computer and use it in GitHub Desktop.
A standard smart pointer
//
// SmartPointer.h
// MemoryDemo
//
// Created by HangChen on 5/5/15.
// Copyright (c) 2015 HangChen. All rights reserved.
//
#ifndef __MemoryDemo__SmartPointer__
#define __MemoryDemo__SmartPointer__
#include <stdio.h>
#import <stdlib.h>
/*
*Usage:
* SmartPointer<SmartPointerValue> v1 = SmartPointer<SmartPointerValue>(new SmartPointerValue(1));
* {
* SmartPointer<SmartPointerValue> v2 = SmartPointer<SmartPointerValue>(new SmartPointerValue(2));
* v1 = v2;
* }
* ///Or you can force it to release
* v1 = NULL;
*/
template <class T> class SmartPointer {
protected:
T *ref;
unsigned *ref_count;
public:
SmartPointer() {
ref = NULL;
ref_count = NULL;
}
SmartPointer(T *ptr) {
ref = ptr;
ref_count = new unsigned;
*ref_count = 1;
}
SmartPointer(SmartPointer<T> const &sptr) {
ref = sptr.ref;
ref_count = sptr.ref_count;
retain();
}
SmartPointer<T>& operator=(SmartPointer<T> const &sptr) {
if (this != &sptr) {
release();
ref = sptr.ref;
ref_count = sptr.ref_count;
retain();
}
return *this;
}
~SmartPointer() {
release();
}
void printDescription() {
unsigned count = 0;
if (ref_count) {
count = *ref_count;
}
printf("%d\n",count);
}
T* getValue() {
return ref;
}
protected:
void retain(){
if (ref_count) {
++*ref_count;
}
}
void release(){
if (ref_count) {
--*ref_count;
if (*ref_count == 0) {
delete ref;
delete ref_count;
ref = NULL;
ref_count = NULL;
}
}
}
};
#endif /* defined(__MemoryDemo__SmartPointer__) */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment