我正在尝试使用模板化对象池,但无法重载放置新运算符。new 运算符适用于默认构造函数,但不适用于非默认构造函数。我在这里粘贴我的简单代码。
#include <boost/pool/object_pool.hpp>
#include <cstddef>
template<typename T>
class objectPool
{
public:
void* operator new (std::size_t num) { void *vp = _pool.malloc(); T *t = ::new(vp)T; return t; }
void* operator new[] (std::size_t num) { void *vp = NULL; assert(0); return vp; }
void operator delete (void *vp) { _pool.free(static_cast<T*>(vp)); return; }
void operator delete [] (void *vp) { assert(0); return; }
private:
static boost::object_pool<T> _pool;
};
template<typename T>
boost::object_pool<T> objectPool<T>::_pool;
class number : public objectPool<number>
{
long long _value1, _value2;
public:
number(long long value1, long long value2) : _value1(value1), _value2(value2) { return; }
~number(){ return; }
void print() { std::cerr<<"_value1:"<<_value1<<"_value2:"<<_value2; return; }
};
int
main(int ac, char **av)
{
number *n = new number(1000, 2000);
n->print();
delete n;
return 0;
}