为ref添加deleter

This commit is contained in:
邹晓航
2015-03-15 18:59:39 +08:00
parent bff1793592
commit c5a3ab8aad
2 changed files with 24 additions and 7 deletions

View File

@@ -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;

View File

@@ -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);