pimpl範例程式碼

來源:互聯網
上載者:User
  • 使用pimpl將實現細節移出標頭檔。

  • 將私人成員變數和私人方法移入Impl類,可以實現資料和方法的封裝,以避免在公開標頭檔中聲明私人方法。

  • 不能在實作類別中隱藏虛方法(virtual method),虛方法必須在公開類中出現以便由繼承類重載。

  • 可以在實作類別中加入指向公開類的指標,以便於Impl類調用公開方法。或者也可以將公開類傳給需要它的實作類別方法。

  • 與Bridge Pattern的區別:The Bridge pattern is about object-oriented design, while the PIMPL idiom is about physical design of files.

  • 解釋:

    But in its basic and common form, a class using PIMPL points to a single implementation, so there is no abstract class with distinct subclasses — just one class, forward declared, and compiled elsewhere. Changing the implementation class does not require any recompilation of sources that include the main header.

    For example, say you have a lot of private member functions, private enums, and private data. And these private "bits" change fairly frequently as the class is developed and maintained. If the #include dependencies are such that touching this header file causes a large number of sources to be recompiled, you have a good candidate for PIMPL.

  • 部署pimpl的方法:Making Pimpl Easy

  • 相關書籍:Large-Scale C++ Software Design

 

AutoTimer.h

#include <boost/shared_ptr.hpp>class AutoTimer{public:/// Create a new timer object with a human readable name AutoTimer(const std::string &name);/// On destruction, the timer reports how long it was alive~AutoTimer();private:// Make this object be noncopyable because it holds a pointerAutoTimer(const AutoTimer &);const AutoTimer &operator =(const AutoTimer &);class Impl;boost::shared_ptr<Impl> mImpl;};

 

AutoTimer.cpp

#include "StdAfx.h"#include "AutoTimer.h"#include <iostream>#include <windows.h>#include <string>class AutoTimer::Impl{public:double GetElapsed() const{return (GetTickCount()-mStartTime) / 1e3;}std::string mName;DWORD mStartTime;};AutoTimer::AutoTimer(const std::string &name): mImpl(new AutoTimer::Impl()){mImpl->mName = name;mImpl->mStartTime = GetTickCount();}AutoTimer::~AutoTimer(void){ std::cout<<mImpl->mName<< ": took " << mImpl->GetElapsed() << " secs" << std::endl;}

Main.cpp

#include "stdafx.h"#include "AutoTimer.h"#include <iostream>using namespace std;int _tmain(int argc, _TCHAR* argv[]){AutoTimer timer("MyTimer");for (int i = 0; i < 10000; ++i){cout << ".";}cout << endl;return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.