[STL 구현] Shared_ptr

huijae0817·2020년 11월 17일
0

Shared포인터에 대한 구현

  • 이것 또한 오늘 면접에서 나왔다
  • 다시 나올 수 있으니 정리

Code(C++)

template<typename T>
class shared_ptr
{
public: 
	shared_ptr();
    explicit shared_ptr(T* ptr);
    shared_ptr(const shared_ptr<T>& rhs);
    ~shared_ptr();
    
    void set(T* ptr) noexcept;
    T* get() const noexcept {return (*_refCount);};
    int use_count() const noexcept {return (*_refCount);};
    bool unique() const noexcept {return {_refCoung ? (*_refCount == 0):false};}
    
    T* operator->() {return _ptr;};
    T& operator* () {return *_ptr;};
    operator bool() const {return (nullptr != _refCount); }
    shared_ptr<TYPE>& operator=(const shared_ptr<T> & rhs);
    
private:
	void add Ref() noexcept;
    void release() noexcept;
private:
	int* _refCount;
    T _ptr
}
#include "shared_ptr.h"
template<typename T>
shared_ptr<T>::shared_ptr():_refCount(nullptr), _ptr(nullptr){}

template<typename T>
shared_ptr<T>::shared_ptr(const shared_ptr<TYPE>& rhs):_refCount(rhs._refCount), _ptr(rhs._ptr){addRef();}

template<typename T>
shared_ptr<T>::~shared_ptr() {release();}

template<typename T>
void shared_ptr<T>::addRef() noexcept
{
	if(nullptr == _refCount)
    {
    	_refCount = new int(0);
    }
    (*_refCount)++;
}

template<typename T>
void shared_ptr<T>::release() noexcept
{
	if(0 == --(*_refCount))
    {
    	delete _refCount;
        delete _ptr;
    }
}

template<typename T>
void shared_ptr<T>::set(T* ptr) noexcept
{
	if(_refCount)
    {
    	release();
        _refCount = nullptr;
        _ptr = nullptr;
    }
    addRef();
    _ptr = ptr;
}

template<typename T>
shared_ptr<T>& shared_ptr<T>::operator=(const shared_ptr<T>&rhs)
{
	_refCount = rhs._refCount;
    _ptr = rhs._ptr;
    
    addRef();
}

단순한 버전(주요 기능만 발췌)

template<typename T>
clase SharedPointer
{
	T* pointer;
    int* reference_count;
public:
	SharedPointer(){}
    SharedPointer(T* object): pointer(object), reference_const(new int(1)){}
    ~SharedPointer(){
    	if(!--(*reference_count))
        {
        	delete reference_count;
            delete pointer;
        }
    }
    SharedPointer(const SharedPointer& oter)
    {
    	this->pointer = other.pointer;
        this->reference_count = other.reference_count;
        (*reference_count)++;
    }
    SharedPointer& operator = (const SharedPointer& other)
    {
    	this->pointer = other.pointer;
        this->reference_count = other.reference_count;
        (*reference_count)++;
        return *this;
    }
    int GetReferenceCount() {return reference_count;}
}

0개의 댓글