Please could somebody verify that my method of implementing Smart Pointer is correct, and if there is maybe a more efficient way of achieving it.
#ifndef SHARED_PTR
#define SHARED_PTR
#include <iostream>
#include <mutex>
using namespace std;
template <class T>
class RCObject
{
T* rawObj;
unsigned int count;
mutex m_Mutx;
public:
RCObject() :rawObj(nullptr), count(0){}
~RCObject()
{
deref();
}
RCObject(T* _rawObj):rawObj(_rawObj)
{
count = 0;
}
int getCount() const
{
return count;
}
T* get()
{
if (rawObj != nullptr) {
return rawObj;
}
return nullptr;
}
void ref()
{
m_Mutx.lock();
count++;
m_Mutx.unlock();
}
void deref()
{
m_Mutx.lock();
count--;
m_Mutx.unlock();
if (count == 0)
{
delete rawObj;
count = 0;
}
}
};
template <class T>
class SharedPtr
{
RCObject<T>* m_Rc;
public:
SharedPtr(T* rawObj)
{
m_Rc = new RCObject<T>(rawObj);
m_Rc->ref();
}
~SharedPtr()
{
m_Rc->deref();
}
SharedPtr()
{
m_Rc = new RCObject<T>();
}
SharedPtr(const SharedPtr& rhs)
{
m_Rc = rhs.m_Rc;
m_Rc->ref();
}
SharedPtr& operator= (const SharedPtr& rhs) {
if (this != &rhs) {
m_Rc->deref();
m_Rc = rhs.m_Rc;
m_Rc->ref();
}
return *this;
}
int getRefCount()
{
return m_Rc->getCount();
}
T* get() const
{
return m_Rc->get();
}
T* operator->() {
return m_Rc->get();
}
};
#endif
shared_ptr
. Also, the title should be the name of what you've created (for example, implementation of reference counted smart pointer). How do I ask a good question? \$\endgroup\$