// delayloader.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <cassert>
using namespace std;
#include <boost/function.hpp>
#include <boost/bind.hpp>
template <class Wapper_Type>
class DelayLoader
{
private:
DelayLoader();
DelayLoader(const DelayLoader<Wapper_Type> &);
DelayLoader<DelayLoader > & operator =(const DelayLoader<Wapper_Type> & );
public:
explicit DelayLoader( boost::function<bool ( Wapper_Type *& ) > loader ): loader_(loader ), data_(NULL), init_(false) {}
~DelayLoader()
{
if (data_ != NULL)
{
delete data_;
data_ = NULL;
}
}
Wapper_Type & operator*()
{
return *Get();
}
Wapper_Type * operator->()
{
return Get();
}
Wapper_Type * Get()
{
if (init_ == false)
{
data_ = new Wapper_Type;
if (data_ == NULL)
{
throw std::runtime_error("ASSERT(data_ == NULL)");
}
else if ( loader_(data_) == false )
{
delete data_;
data_ = NULL;
throw std::runtime_error("ASSERT(loader_(data_) == false)");
}
init_ = true;
}
return data_;
}
void Clear()
{
delete data_;
data_ = NULL;
init_ = false;
}
void Reload()
{
if (init_ == true)
{
Wapper_Type * data = new Wapper_Type;
if (data == NULL)
{
throw std::runtime_error("ASSERT(data == NULL)");
}
else if ( loader_(data) == false )
{
delete data;
data = NULL;
throw std::runtime_error("ASSERT(loader_(data) == false)");
}
delete data_;
data_ = data;
}
}
private:
boost::function<bool ( Wapper_Type *& ) > loader_;
Wapper_Type * data_;
bool init_;
};
bool readcfg(int mid, int * gold)
{
if (mid == 0)
{
*gold = 1;
}
else
{
*gold = 2;
}
return true;
}
bool readcfg(int mid, const string & pw, int * gold)
{
if (pw.empty() && mid == 0)
{
*gold = 3;
}
else
{
*gold = 4;
}
return true;
}
class point
{
public:
int x_;
int y_;
};
bool readpoint(point * p)
{
p->x_ = 1;
p->y_ = 2;
return true;
}
bool readpoint_false(point * p)
{
return false;
}
int _tmain(int argc, _TCHAR* argv[])
{
DelayLoader<int > int_0(boost::bind( readcfg, 0, _1) );
cout<<*int_0<<endl;
DelayLoader<int > int_1(boost::bind( readcfg, 1, "passwd", _1) );
cout<<*int_1<<endl;
DelayLoader<point > pint_1(boost::bind( readpoint, _1) );
cout<<"x_:="<<pint_1->x_<<", y_:="<<pint_1->y_<<endl;
{
DelayLoader<point > pint_1(boost::bind( readpoint_false, _1) );
assert(pint_1.Get() == NULL);
assert(pint_1.Get() == NULL);
}
return 0;
}
在游戏服务器端编程时,常发现有些玩家数据可以延时加载,即:需要用的时候,再加载,于是,写了这个一个包装类。。。
请各位大侠指正!