我努力使自己實現shared_ptr
。我遇到問題make_shared
。的std::make_shared
的主要特徵在於它分配計數器塊和對象在連續的存儲器塊。我如何做同樣的事情?Make_shared - 自己實現
我試圖做這樣的事情:
template<class T>
class shared_ptr
{
private:
class _ref_cntr
{
private:
long counter;
public:
_ref_cntr() :
counter(1)
{
}
void inc()
{
++counter;
}
void dec()
{
if (counter == 0)
{
throw std::logic_error("already zero");
}
--counter;
}
long use_count() const
{
return counter;
}
};
template<class _T>
struct _object_and_block
{
_T object;
_ref_cntr cntr_block;
template<class ... Args>
_object_and_block(Args && ...args) :
object(args...)
{
}
};
T* _obj_ptr;
_ref_cntr* _ref_counter;
void _check_delete_ptr()
{
if (_obj_ptr == nullptr)
{
return;
}
_ref_counter->dec();
if (_ref_counter->use_count() == 0)
{
_delete_ptr();
}
_obj_ptr = nullptr;
_ref_counter = nullptr;
}
void _delete_ptr()
{
delete _ref_counter;
delete _obj_ptr;
}
template<class _T, class ... Args>
friend shared_ptr<_T> make_shared(Args && ... args);
public:
shared_ptr() :
_obj_ptr(nullptr),
_ref_counter(nullptr)
{
}
template<class _T>
explicit shared_ptr(_T* ptr)
{
_ref_counter = new counter_block();
_obj_ptr = ptr;
}
template<class _T>
shared_ptr(const shared_ptr<_T> & other)
{
*this = other;
}
template<class _T>
shared_ptr<T> & operator=(const shared_ptr<_T> & other)
{
_obj_ptr = other._obj_ptr;
_ref_counter = other._ref_counter;
_ref_counter->inc();
return *this;
}
~shared_ptr()
{
_check_delete_ptr();
}
};
template<class T, class ... Args>
shared_ptr<T> make_shared(Args && ... args)
{
shared_ptr<T> ptr;
auto tmp_object = new shared_ptr<T>::_object_and_block<T>(args...);
ptr._obj_ptr = &tmp_object->object;
ptr._ref_counter = &tmp_object->cntr_block;
return ptr;
}
但是當我刪除對象和計數器塊,無效的堆塊發生異常。
圍繞共享指針管理的兩個強制性代碼片段是(a)引用計數算法,以及(b)實際的* delete *,這兩個選項都不包括在本文中。我們不介意讀者。發佈展示實際問題的[**完整MCVE **](http://stackoverflow.com/help/mcve)。聲明「當我刪除對象和計數器塊...」表明你正在刪除兩個從未被直接分配的東西(實際上唯一的直接分配tmp_object永遠不會被保留)。 – WhozCraig 2014-12-09 11:39:07
@WhozCraig謝謝!我已更新帖子 – 2014-12-09 12:33:19
您的實施缺少一些關鍵功能。如果添加它們,解決方案可能會簡單地顯示在現有代碼之外。缺少的東西:刪除器的類型擦除,存儲與託管對象無關的指針(也許更多,比如線程安全的引用計數,弱引用計數,..)'shared_ptr'是複雜的,並且花費很長時間來開發目前的形式。 – dyp 2014-12-09 12:50:01