The following is the finalized code for a simple C++ smart pointer as demonstrated by my youtube video:
here
Usage:
void main(){
...
Pointer<ObjectType> pointer(new ObjectType);
...
}
- /*
- * Pointer.h
- *
- * Created on: Mar 16, 2012
- * Author: ukaku
- */
- #ifndef POINTER_H_
- #define POINTER_H_
- #include <iostream>
- using namespace std;
- /**
- * Reference represents a counter that will be incremented or decremented as
- * the number of references to a pecticular pointer is made;
- *
- * where data means: a symbol used to point to, or associate to another object
- */
- class ReferenceCounter{
- private:
- int counter;
- public:
- ReferenceCounter(){
- counter=0; //initially set to zero
- }
- void increase(){
- counter++; //increase it
- }
- int decrease(){
- --counter; //decrease it
- if(counter<0){
- cout << "ReferenceCouner is < 0"<<endl;
- }
- return counter; //return its current value
- }
- int getCount(){
- return counter; //simply return the current value
- }
- };
- template<class T>
- /**
- * Behaves as a smart pointer
- */
- class Pointer {
- T* data;
- ReferenceCounter* dataReferenceCounter;
- public:
- Pointer() : data(NULL), dataReferenceCounter(NULL){
- //set everything to null but allocate a new reference counter
- dataReferenceCounter = new ReferenceCounter();
- dataReferenceCounter->increase();
- }
- Pointer(T* xReference) : data(xReference), dataReferenceCounter(NULL){
- dataReferenceCounter = new ReferenceCounter();
- dataReferenceCounter->increase();
- }
- dataReferenceCounter->increase();
- }
- /**
- * Assignment operator
- */
- Pointer<T>& operator=(const Pointer<T> &other) {
- //prevent self assignment
- if(this != &other){
- //decrease this current instances counter because we are about to override it
- if(dataReferenceCounter->decrease()==0){
- delete data;
- delete dataReferenceCounter;
- }
- data = other.data;
- dataReferenceCounter = other.dataReferenceCounter;
- dataReferenceCounter->increase();
- }
- return *this;
- }
- //!Only delete the data if and only if no other smart pointer
- //!has a data this to data
- if(dataReferenceCounter->decrease() == 0){
- delete data;
- delete dataReferenceCounter;
- }
- }
- T& operator*(){
- return *data;
- }
- T* operator->(){
- return data;
- }
- };
- #endif /* POINTER_H_ */
Comments
Post a Comment