提交 c5a3ab8a 编写于 作者: 邹晓航

为ref添加deleter

上级 bff17935
......@@ -2,27 +2,44 @@
#define _REF_H_
#include <atomic>
#include <functional>
#include <memory>
namespace TinySTL{
namespace Detail{
template<class T>
struct _default_delete{
void operator ()(T* ptr){ if (ptr) delete ptr; }
};
template<class T>
struct ref_t{
using deleter_type = std::function < void(T*) >;
std::atomic<size_t> ncount_;
T *data_;
explicit ref_t(T *p = nullptr): ncount_(0), data_(p){
deleter_type deleter_;
explicit ref_t(T *p = nullptr, deleter_type pfunc = deleter_type(_default_delete<T>()))
: ncount_(0), data_(p), deleter_(pfunc){
if (data_)
ncount_ = 1;
}
ref_t(const ref_t&) = delete;
ref_t& operator = (const ref_t&) = delete;
~ref_t(){
--ncount_;
if (ncount_ == 0)
deleter_(data_);
}
size_t count()const{ return ncount_.load(); }
T *get_data()const{ return data_; }
ref_t& operator ++(){
++ncount_;
return *this;
ref_t& operator ++(){
++ncount_;
return *this;
}
ref_t operator ++(int){
auto t = *this;
......
......@@ -7,8 +7,8 @@ namespace TinySTL{
assert(r1.count() == 0);
assert(r1.get_data() == nullptr);
int n = 0;
ref_t<int> r2(&n);
int *p = new int(0);
ref_t<int> r2(p);
assert(r2.count() == 1);
assert(r2.get_data() != nullptr);
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册