实现boost::obj_pool,大神请绕道

直接上代码


#ifndef BOOST_OBJECTPOOL_HPP
#define BOOST_OBJECTPOOL_HPP

#include <boost/pool/poolfwd.hpp>
#include <boost/pool/pool.hpp>


#if defined(BOOST_MSVC) || defined(__KCC)
# define BOOST_NO_TEMPLATE_CV_REF_OVERLOADS
#endif


#ifdef __BORLANDC__
# pragma option push -w-inl
#endif


template <typename T, typename UserAllocator = boost::default_user_allocator_new_delete>
class cObjectPool : protected boost::pool < UserAllocator >
{ //!
public:
	typedef T element_type; //!< ElementType
	typedef UserAllocator user_allocator; //!<
	typedef typename boost::pool<UserAllocator>::size_type size_type; //!<   boost::pool<UserAllocator>::size_type
	typedef typename boost::pool<UserAllocator>::difference_type difference_type; //!< boost::pool<UserAllocator>::difference_type

protected:
	//! \return The underlying boost:: \ref boost::pool storage used by *this.
	boost::pool<UserAllocator> & store()
	{
		return *this;
	}
	//! \return The underlying boost:: \ref boost::pool storage used by *this.
	const boost::pool<UserAllocator> & store() const
	{
		return *this;
	}

	// for the sake of code readability :)
	static void * & nextof(void * const ptr)
	{ //! \returns The next memory block after ptr (for the sake of code readability :)
		return *(static_cast<void **>(ptr));
	}

public:
	explicit cObjectPool(const size_type arg_next_size = 32, const size_type arg_max_size = 0)
		:
		boost::pool<UserAllocator>(sizeof(T), arg_next_size, arg_max_size)
	{ //! Constructs a new (empty by default) ObjectPool.
		//! \param next_size Number of chunks to request from the system the next time that object needs to allocate system memory (default 32).
		//! \pre next_size != 0.
		//! \param max_size Maximum number of chunks to ever request from the system - this puts a cap on the doubling algorithm
		//! used by the underlying boost::pool.
	}

	~cObjectPool();

	// Returns 0 if out-of-memory.
	element_type * malloc BOOST_PREVENT_MACRO_SUBSTITUTION()
	{ //! Allocates memory that can hold one object of type ElementType.
		//!
		//! If out of memory, returns 0. 
		//!
		//! Amortized O(1).
		return static_cast<element_type *>(store().ordered_malloc());
	}
	void free BOOST_PREVENT_MACRO_SUBSTITUTION(element_type * const chunk)
	{ //! De-Allocates memory that holds a chunk of type ElementType.
		//!
		//!  Note that p may not be 0.\n
		//!
		//! Note that the destructor for p is not called. O(N).
		store().ordered_free(chunk);
	}
	bool is_from(element_type * const chunk) const
	{ /*! \returns true  if chunk was allocated from *this or
	  may be returned as the result of a future allocation from *this.

	  Returns false if chunk was allocated from some other boost::pool or
	  may be returned as the result of a future allocation from some other boost::pool.

	  Otherwise, the return value is meaningless.

	  \note This function may NOT be used to reliably test random pointer values!
	  */
		return store().is_from(chunk);
	}
	template <class... Args>
	element_type * construct(Args&&...args)
	{ //! \returns A pointer to an object of type T, allocated in memory from the underlying boost::pool
		//! and default constructed.  The returned objected can be freed by a call to \ref destroy.
		//! Otherwise the returned object will be automatically destroyed when *this is destroyed.
		element_type * const ret = (malloc)();
		if (ret == 0)
			return ret;
		try { new (ret)element_type(args...); }
		catch (...) { (free)(ret); throw; }
		return ret;
	}


	void destroy(element_type * const chunk)
	{ //! Destroys an object allocated with \ref construct. 
		//!
		//! Equivalent to:
		//!
		//! p->~ElementType(); this->free(p);
		//!
		//! \pre p must have been previously allocated from *this via a call to \ref construct.
		chunk->~T();
		(free)(chunk);
	}

	size_type get_next_size() const
	{ //! \returns The number of chunks that will be allocated next time we run out of memory.
		return store().get_next_size();
	}
	void set_next_size(const size_type x)
	{ //! Set a new number of chunks to allocate the next time we run out of memory.
		//! \param x wanted next_size (must not be zero).
		store().set_next_size(x);
	}
};

template <typename T, typename UserAllocator>
cObjectPool<T, UserAllocator>::~cObjectPool()
{
#ifndef BOOST_POOL_VALGRIND
	// handle trivial case of invalid list.
	if (!this->list.valid())
		return;

	boost::details::PODptr<size_type> iter = this->list;
	boost::details::PODptr<size_type> next = iter;

	// Start 'freed_iter' at beginning of free list
	void * freed_iter = this->first;

	const size_type partition_size = this->alloc_size();

	do
	{
		// increment next
		next = next.next();

		// delete all contained objects that aren't freed.

		// Iterate 'i' through all chunks in the memory block.
		for (char * i = iter.begin(); i != iter.end(); i += partition_size)
		{
			// If this chunk is free,
			if (i == freed_iter)
			{
				// Increment freed_iter to point to next in free list.
				freed_iter = nextof(freed_iter);

				// Continue searching chunks in the memory block.
				continue;
			}

			// This chunk is not free (allocated), so call its destructor,
			static_cast<T *>(static_cast<void *>(i))->~T();
			// and continue searching chunks in the memory block.
		}

		// free storage.
		(UserAllocator::free)(iter.begin());

		// increment iter.
		iter = next;
	} while (iter.valid());

	// Make the block list empty so that the inherited destructor doesn't try to
	// free it again.
	this->list.invalidate();
#else
	// destruct all used elements:
	for (std::set<void*>::iterator pos = this->used_list.begin(); pos != this->used_list.end(); ++pos)
	{
		static_cast<T*>(*pos)->~T();
	}
	// base class will actually free the memory...
#endif
}



// The following code might be put into some Boost.Config header in a later revision
#ifdef __BORLANDC__
# pragma option pop
#endif

#endif

主要修改地方为 构造函数,去掉了原有的限制

template <class... Args>
	element_type * construct(Args&&...args)
	{ //! \returns A pointer to an object of type T, allocated in memory from the underlying boost::pool
		//! and default constructed.  The returned objected can be freed by a call to \ref destroy.
		//! Otherwise the returned object will be automatically destroyed when *this is destroyed.
		element_type * const ret = (malloc)();
		if (ret == 0)
			return ret;
		try { new (ret)element_type(args...); }
		catch (...) { (free)(ret); throw; }
		return ret;
	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

敬我岁月无波澜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值