Kindly provide your review comments:
//SmartPtr.h
class RefCount {
public:
void AddRef() {
++(this->_count);
}
int Release() {
return --(this->_count);
}
private:
int _count;
};
template <class T>
class SmartPtr {
public:
// constructor
SmartPtr();
SmartPtr(T* iObject);
// copy constructor
SmartPtr(const SmartPtr<T>& iSPtr);
// destructor
~SmartPtr();
// operators
SmartPtr<T>& operator=(const SmartPtr<T>& iSPtr);
T& operator*();
T* operator->();
private:
T* _ptr;
RefCount* _refCount;
void _release();
void _copySmartPtr(const SmartPtr<T>& iSPtr);
};
//SmartPtr.cpp
#include "SmartPtr.h"
// constructor
template <class T>
SmartPtr<T>::SmartPtr():
_refCount(nullptr),
_ptr(nullptr)
{
}
template <class T>
SmartPtr<T>::SmartPtr(T* iObject):
_refCount(new RefCount()),
_ptr(iObject)
{
this->_refCount->AddRef();
}
// copy constructor
template <class T>
SmartPtr<T>::SmartPtr(const SmartPtr<T>& iSPtr)
{
this->_copySmartPtr(iSPtr);
}
// destructor
template <class T>
SmartPtr<T>::~SmartPtr() {
this->_release();
}
// operators
template <class T>
SmartPtr<T>& SmartPtr<T>::operator=(const SmartPtr<T>& iSPtr) {
if (iSPtr._ptr && (this != &iSPtr)) {
this->_release();
this->_copySmartPtr(iSPtr);
}
return *this;
}
template <class T>
T& SmartPtr<T>::operator*() {
return *(this->_ptr);
}
template <class T>
T* SmartPtr<T>::operator->() {
return this->_ptr;
}
template <class T>
void SmartPtr<T>::_release() {
if (this->_refCount && this->_refCount->Release() == 0) {
delete this->_ptr;
delete this->_refCount;
}
}
template <class T>
void SmartPtr<T>::_copySmartPtr(const SmartPtr<T>& iSPtr) {
this->_ptr = iSPtr._ptr;
this->_refCount = iSPtr._refCount;
this->_refCount->AddRef();
}
std::unique_ptr
orstd::shared_ptr
? \$\endgroup\$SmartPtr
” is a bad name. It doesn’t tell the user what it actually does. Choose a name that’s descriptive, such asSharedPtr
orRefCountedPtr
. \$\endgroup\$