65,211
社区成员
发帖
与我相关
我的任务
分享
#include <map>
#include <iostream>
#include <stdlib.h>
using namespace std;
template<typename ACE_LOCK,
typename K,
typename V,
template<typename Key,typename Value,typename = less<Key>,typename = std::allocator<std::pair<const Key,Value> >
class Cont = map >
class CMEMContainer {
public:
CMEMContainer() {};
virtual V* allocate(const K& rhs)
{
void *ptr;
V *elem;
typename Cont<K,V*>::iterator it;
it = this->container_.find(rhs);
if(it != this->container_.end())
{
ptr = (*it).second;
}
else
{
ptr = (void*)malloc(sizeof(V));
}
if(NULL == ptr)
{
return ptr;
}
elem = new (ptr) V;
if(it == this->container_.end())
this->container_.insert(make_pair(rhs,elem));
return elem;
}
virtual void reclaim(const K& rhs,V* ptr)
{
typename Cont<K,V*>::iterator it;
it = this->container_.find(rhs);
if(it != this->container_.end() && (*it).second == ptr)
{
ptr->~V();
}
return;
}
~CMEMContainer()
{
for(typename Cont<K,V*>::iterator it = this->container_.begin(); it != this->container_.end(); ++it)
{
free((*it).second);
}
}
private:
ACE_LOCK lock_;
Cont<K,V*> container_;
};
int main()
{
CMEMContainer<int,int,int,map> i;
}
template<typename ACE_LOCK,
typename K,
typename V,
template<typename K,typename V>
class CONT = map>
template<typename ACE_LOCK,
typename K,
typename V,
template<typename Key,typename Value,typename = less<Key>,typename = std::allocator<std::pair<const Key,Value> > > //最后那个>
class Cont = map >
class CMEMContainer
{
struct cookie
{
bool empty; //表示buf上是否构造了V对象
char buf[sizeof(V)];
};
public:
typedef Cont<K, cookie> cont_t;
CMEMContainer() {};
virtual V* allocate(const K& rhs)
{
cookie * node;
typename cont_t::iterator it = this->container_.find(rhs);
if(it == this->container_.end())
{
cookie ck;
ck.empty = true;
node = &(this->container_.insert(make_pair(rhs, ck)).first->second);
}
else
node = &((*it).second);
if(node->empty)
{
node->empty = false;
return new (node->buf) V;
}
return 0;
}
virtual void reclaim(const K& rhs)
{
typename cont_t::iterator it;
it = this->container_.find(rhs);
if(it != this->container_.end())
{
if(!it->second.empty)
{
reinterpret_cast<V*>(it->second.buf)->~V();
it->second.empty = true;
}
}
return;
}
~CMEMContainer()
{
for(typename cont_t::iterator it = this->container_.begin(); it != this->container_.end(); ++it)
{
if(!it->second.empty)
reinterpret_cast<V*>(it->second.buf)->~V();
}
}
private:
ACE_LOCK lock_;
cont_t container_;
};