The "Fast Pimpl" Idiom

// file y.h
class X;
class Y
{	
	/*...*/
	X* px_;	
};

// file y.cpp


#include "x.h"

Y::Y() : px_( new X ) {}

Y::~Y() { delete px_; px_ = 0; }


// This nicely hides X, but it turns out that Y is used very widely and the dynamic allocation 
// overhead is degrading performance.

// Attempt #3 
// file y.h
class Y
{	
	/*...*/	
	static const size_t sizeofx = /*some value*/;
	char x_[sizeofx];	
};

// file y.cpp
#include "x.h"
Y::Y()
{
	assert( sizeofx >= sizeof(X) );
	new (&x_[0]) X;
}

Y::~Y()
{	
	(reinterpret_cast<X*>(&x_[0]))->~X();	
}

// file x.h 


class X
{	
	/*...*/	
	struct XImpl;
	XImpl* pimpl_;	
};

// file x.cpp
#include "x.h"
struct X::XImpl
{
	/*...private stuff here...*/	
	static void* operator new( size_t )   { /*...*/ }
	static void  operator delete( void* ) { /*...*/ }	
};

X::X() : pimpl_( new XImpl ) {}
X::~X() { delete pimpl_; pimpl_ = 0; }

template<size_t S> 


class FixedAllocator
{	
public:	
	void* Allocate( /*requested size is always S*/ );	
	void  Deallocate( void* );	
private:
	/*...implemented using statics?...*/	
};


class FixedAllocator 
{
public:
  static FixedAllocator& Instance();
  void* Allocate( size_t );
  void  Deallocate( void* );

private:
  /*...singleton implementation, typically
       with easier-to-manage statics than
       the templated alternative above...*/
};

struct FastArenaObject 
{
	static void* operator new( size_t s )	
	{
		return FixedAllocator::Instance()->Allocate(s);		
	}
	static void operator delete( void* p )	
	{	
		FixedAllocator::Instance()->Deallocate(p);
	}
	
};

//  Want this one to be a Fast Pimpl? 
//  Easy, then just inherit...

struct X::XImpl : FastArenaObject

{	
	/*...private stuff here...*/	
};

//  have some problem, i don't see it. 30


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值