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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
pimpl(Pointer to Implementation)是一种设计模式,用于隐藏类的实现细节。该模式的主要目的是将类的接口和实现分离,以便提高代码的可维护性和可扩展性。 在传统的C++开发,类的实现细节通常会暴露在类的头文件,这样会导致头文件的内容变得庞大且混乱。而pimpl模式通过在类使用指向实现类的指针,将实现细节脱离类的接口部分,使得头文件只需包含一个简单的指针声明,从而实现了隐藏指针的效果。 使用pimpl模式隐藏指针有多个好处。首先,它可以提高编译速度,因为只有头文件的改变才会导致需要重新编译的文件数量减少;其次,它可以减少对外部用户的依赖,当类的实现发生变化时,只需要重新编译实现文件而无需重新编译使用该类的其他文件;此外,pimpl模式还可以提高二进制兼容性,因为只有指针的大小发生变化,而不是整个类的大小。 使用pimpl模式时,首先需要在类的头文件声明一个指向实现类的指针,并在类的实现文件定义实现类。然后,在类的构造函数和析构函数创建和销毁实现类的对象,并在类的成员函数通过指针访问实现类的成员。 因此,pimpl模式允许将实现细节从类的接口分离出来,提高了代码的可维护性和可扩展性。使用pimpl隐藏指针的设计模式可以提高编译速度、减少对外部用户的依赖以及提高二进制兼容性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值