春暖花开
雪化了,花开了,春天来了
posts - 149,comments - 125,trackbacks - 0
今天在首页看到的,感觉不错,摘过来保存一下:
http://www.cppblog.com/CornerZhang/archive/2009/04/13/79004.html

内容如下:

 头文件依赖,Pimpl法,加速编译
   举个例子:
      // File: SoundSystem.h

      #include "StreamFilter.h"
      #include "Emitters."

      class SoundSystem {
      public:
         // ...
      private:
         StreamFilter currentFilter;
         EmitModeConfig modeConfig;
      };
   一目了然的是,看得出SoundSystem实现使用了StreamFilter和EmitModeConfig的定义,所以#include 了他们的定义在此SoundSystem.h中,可是随着项目的不断推进,class SoundSystem中依赖的使用类型会增多,它的header被引入到其它模块中,不知不觉的编译时间越来越长,改进之:
      // File: SoundSystem.h

      class StreamFilter;
      class EmitModeConfig;

      class SoundSystem {
      public:
         // ...
      private:
         StreamFilter* currentFilterPtr;
         EmitModeConfig* modeConfigPtr;
      };

      // File: SoundSystem.cpp
      #include "StreamFilter.h"
      #include "Emitters."

      SoundSystem::SoundSystem() {
         //...
         currentFilterPtr = new StreamFilter;
         modeConfigPtr = new EmitModeConfig;
      }

      SoundSystem::~SoundSystem() {
         delete currentFilterPtr;
         delete modeConfigPtr;
         //...
      }
      这么一来,把StreamFilter和EmitModeConfig的#include藏到了SoundSystem的实现代码中,以后对SoundSystem的部分改动不会导致其它模块的rebuild哦,不过由此可能会牺牲一点效率吧!

      记得,有位微软的C++翘楚人物,Herb Sutter给这种技巧称为Pimpl ( Private Implemention ), 用的恰到好处时,可以提高项目开发速度,同时模块的头文件间的#include关系得以缓解,可以避开循环依赖,而且可以获得一个良好的物理设计。

总结:
      Pimpl方法感觉很不错,
      使用这个方法的时候,一定要注意的是在这个地方的变化,这个是我第二遍看的时候才注意到的.
     class SoundSystem {
      public:
         // ...
      private:
         StreamFilter currentFilter;
         EmitModeConfig modeConfig;

      };

      采用Pimpl方法后,变为
     class SoundSystem {
      public:
         // ...
      private:
         StreamFilter* currentFilterPtr;
         EmitModeConfig* modeConfigPtr;

      };
      所以在.cpp文件中就有了new和delete的操作.

      对于这种方法有一个疑问?对于那种存在包含众多类的情况下,这种方法的驾驭不是一般人能够掌握的吧.或许这种方法就不太使用了,不如等待一会,编译.


posted on 2009-04-16 10:11 Sandy 阅读(2851) 评论(1)  编辑 收藏 引用 所属分类: C++

FeedBack:
# re: 转:C++ 代码技巧_头文件依赖,Pimpl法
2011-07-07 13:36 | askhao
在类得初始化列表中new就可以了啊,很方便的。  回复  更多评论
  

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理