Home made Smart Pointer in C++

My = opreator isn't working how id want it to any help would be ap

Page 1 of 1

1 Replies - 775 Views - Last Post: 04 September 2009 - 09:55 PM Rate Topic: -----

#1 CorporateSpo  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 04-September 09

Home made Smart Pointer in C++

Posted 04 September 2009 - 07:33 PM

I know this isnt the greatest place to post this but this forum has the fastest response times iv found. This is my main file im having an error on the line SmartPtr<int> q = p; Its causing a seg fault and a talking talking about possible corrupted stack so im wondering if im getting some memory leakage. So first is my main code and then my SmartPtr.h file.

#include "SmartPtr.h"
#include <string>
#include <iostream>

using namespace SmartPtrNames;

int main(int argc, char *argv[])
{
// some simple tests
SmartPtr<int> p = new int();
*p = 5;
printAllCounts("first");
cout << "p = " << *p << &p << endl;
SmartPtr<int> q = p;
cout << "p = " << *p << " q = " << *q << endl;
printAllCounts("second");
SmartPtr<int> r = new int();
*r = 2;
printAllCounts("third");
p = r;
cout << "p = " << *p << " q = " << *q << " r = " << *r << endl;
printAllCounts("fourth");
q = p;
cout << "p = " << *p << " q = " << *q << " r = " << *r << endl;
q = p = r = 0;
printAllCounts("fifth");

return 1;
}

namespace SmartPtrNames
{
using namespace std;
void printAllCounts(char* word)
{
};
}

#ifndef _SMARTPTR_H
#define _SMARTPTR_H

template <class T>
class SmartPtr {

public:
SmartPtr(T* ptr = 0) : itsCounter(0)
{
if (ptr) itsCounter = new counter(ptr);
};

~SmartPtr()
{
release();
};

SmartPtr(const SmartPtr<T>& sptr)
{
acquire(sptr.itsCounter);
};

SmartPtr<T>& operator= (const SmartPtr<T>& sptr)
{
if (this != &sptr) {
release();
acquire(sptr.itsCounter);
}
return *this;

};

T* operator->() {};
T& operator*() {};

private:

struct counter {
counter(T* p = 0, unsigned c = 1) : ptr(p), count(c) {}
T* ptr;
unsigned count;
}* itsCounter;

void acquire(counter* c) throw()
{ // increment the count
itsCounter = c;
if (c) ++c->count;
}

void release()
{ // decrement the count, delete if it is 0
if (itsCounter) {
if (--itsCounter->count == 0) {
delete itsCounter->ptr;
delete itsCounter;
}
itsCounter = 0;
}
}


};

#endif /* _SMARTPTR_H */



Is This A Good Question/Topic? 0
  • +

Replies To: Home made Smart Pointer in C++

#2 ccubed  Icon User is offline

  • It's That Guy
  • member icon

Reputation: 162
  • View blog
  • Posts: 1,409
  • Joined: 13-June 08

Re: Home made Smart Pointer in C++

Posted 04 September 2009 - 09:55 PM

SmartPtr is a class..So, *p isn't dereferencing the value pointed to by the pointer, but trying to dereference the class to a value.

IE: p is a class. if p was a ptr to a class, *p would refer to the class. In this case, *p doesn't exist even if you set it equal to new int().
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1