C++ shared ptr implementation

#include <iostream>
#include <memory>
template <typename T>
class SharedPtr
{
public:
explicit SharedPtr(T* ptr)
{
mPtr = ptr;
mCount = new int(1);
}
~SharedPtr()
{
(*mCount)--;
if (*mCount == 0) {
delete mPtr;
delete mCount;
}
}
// copy constructor
SharedPtr(const SharedPtr& rhs)
{
mPtr = rhs.mPtr;
mCount = rhs.mCount;
(*mCount)++;
}
// copy assignment op
SharedPtr& operator=(const SharedPtr& rhs)
{
if (this != &rhs) {
mPtr = rhs.mPtr;
(*mCount)++;
}
return *this;
}
T& operator*()
{
return *mPtr;
}
T* operator->()
{
// The overload of operator -> must either return a raw pointer,
// or return an object (by reference or by value)
// for which operator -> is in turn overloaded.
return mPtr;
}
// for logging
friend std::ostream& operator<<(std::ostream& os, SharedPtr<T>& sp)
{
os << "value:" << *sp << std::endl;
return os;
}
private:
int* mCount{nullptr};
T* mPtr{nullptr};
};
int main()
{
SharedPtr<int> p(new int(3));
SharedPtr<int> q(p);
SharedPtr<int> r = p;
std::cout << *p << std::endl;
std::cout << *q << std::endl;
std::cout << *r << std::endl;
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store