Skip to content

Instantly share code, notes, and snippets.

@mrchaofan
Last active February 14, 2023 14:32
Show Gist options
  • Save mrchaofan/a34825e87a16bb2c8125b26165d71f57 to your computer and use it in GitHub Desktop.
Save mrchaofan/a34825e87a16bb2c8125b26165d71f57 to your computer and use it in GitHub Desktop.
shared pointer implementation for education purpose.
#include <iostream>
template <typename T>
class shared_ptr
{
public:
shared_ptr() noexcept : mpValue(nullptr), mpRefCount(nullptr)
{
}
shared_ptr(std::nullptr_t) noexcept : mpValue(nullptr), mpRefCount(nullptr)
{
}
explicit shared_ptr(T* pValue) : mpValue(pValue), mpRefCount(new size_t(1))
{
}
shared_ptr(const shared_ptr<T>& sharedPtr) noexcept : mpValue(sharedPtr.mpValue), mpRefCount(sharedPtr.mpRefCount)
{
if (mpRefCount != nullptr)
{
++(*mpRefCount);
}
}
shared_ptr(shared_ptr<T>&& sharedPtr) noexcept : mpValue(sharedPtr.mpValue), mpRefCount(sharedPtr.mpRefCount)
{
sharedPtr.mpValue = nullptr;
sharedPtr.mpRefCount = nullptr;
}
~shared_ptr() noexcept
{
if (mpRefCount != nullptr)
{
if (--(*mpRefCount) == 0)
{
delete mpRefCount;
delete mpValue;
}
}
}
shared_ptr& operator=(const shared_ptr<T>& sharedPtr) noexcept
{
if (&sharedPtr != this) {
shared_ptr<T>(shared_ptr).swap(*this);
}
return *this;
}
shared_ptr& operator=(shared_ptr<T>&& sharedPtr) noexcept
{
if (&sharedPtr != this)
{
shared_ptr<T>(std::move(sharedPtr)).swap(*this);
}
return *this;
}
T* get() noexcept
{
return mpValue;
}
private:
T* mpValue;
size_t* mpRefCount;
void swap(shared_ptr<T>& sharedPtr) noexcept
{
T* pValue = sharedPtr.mpValue;
sharedPtr.mpValue = mpValue;
mpValue = pValue;
size_t* pRefCount = sharedPtr.mpRefCount;
sharedPtr.mpRefCount = mpRefCount;
mpRefCount = pRefCount;
}
};
class A
{
public:
int mno;
A(int no) : mno(no)
{
std::cout << "A(" << mno << ")" << std::endl;
}
~A()
{
std::cout << "~A(" << mno << ")" << std::endl;
}
};
int main()
{
{
std::cout << ">>>" << std::endl;
A* obj = new A{ 1 };
A* obj2 = new A{ 2 };
shared_ptr<A> a{ obj };
{
std::cout << ">>>" << std::endl;
shared_ptr<A> b{ obj2 };
a = std::move(b);
std::cout << "<<<" << std::endl;
}
std::cout << "<<<" << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment