|
-
January 19th, 2010, 05:19 AM
#1
C++ Smart Pointer Question
Hello ,
I'm a little rusty on c++ so i want to ask a questions to the gurus.
I am trying to create a smart pointer(dont wanna use boost) and i want to know if the following implementation is ok :
Code:
#ifndef SMARTPTR_H_
#define SMARTPTR_H_
#ifdef __DEBUG__SESSION
#include <stdio.h>
#endif
namespace smartptr {
inline void DEBUG(const char *msg) {
#ifdef __DEBUG__SESSION
printf("%s\n",msg);
#endif
}
template<typename T>
class SmartPtr {
T *m_ptr;
bool m_isCollection;
int *m_refCount;
int temp;
public:
SmartPtr() :
m_refCount(0), m_ptr(0), m_isCollection(0) {
DEBUG("Default constructor.");
}
SmartPtr(T* ptr, bool isCollection = false) :
m_refCount(0) {
DEBUG("T* constructor.");
reset(ptr, isCollection);
}
SmartPtr(const SmartPtr &other) :
m_refCount(0) {
reset(other.m_ptr, other.m_isCollection);
other.release();
DEBUG("Copy constructor.");
}
T* get() const {
DEBUG("GET.");
return m_ptr;
}
bool isValid() const {
return (m_ptr != 0);
}
void reset(T* ptr, bool isCollection = false) {
destroy();
m_refCount = &temp;
m_ptr = ptr;
m_isCollection = isCollection;
*m_refCount = 1;
DEBUG("Reset.");
}
T* release() const {
T* ptr = m_ptr;
if (m_refCount) {
(*m_refCount)++;
}
DEBUG("Released pointer ownership.");
return ptr;
}
void destroy() {
if (m_ptr && m_refCount) {
(*m_refCount)--;
if (*m_refCount == 0) {
if (m_isCollection) {
delete[] m_ptr;
m_ptr = 0;
DEBUG("Destroyed collection.");
return;
}
delete m_ptr;
m_ptr = 0;
DEBUG("Destroyed single pointer.");
}
}
if (m_refCount != 0) {
m_refCount = 0;
}
}
T* operator ->() const {
return get();
}
T& operator *() const {
return *get();
}
const SmartPtr& operator=(T* ptr) {
reset(ptr);
DEBUG("Op = T*.");
return *this;
}
const SmartPtr& operator=(const SmartPtr<T> &other) {
DEBUG("Equals");
reset(other.m_ptr, other.m_isCollection);
other.release();
return *this;
}
~SmartPtr() {
destroy();
}
};
}
#endif /* SMARTPTR_H_ */
I need to know especially the part where the reference counter is involved. I want to keep everything in the class on the stack so the m_refCount to a stack location. Is this illegal and if yes what are the dangers. Thx in advance.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|