C++的PIMPL實現

private Implementation
  1.降低模塊耦合度
  2.降低編譯依賴,提高編譯速度
  3.接口與實現分離,提高接口穩定性
  
  原理:在公共接口裏封裝私有數據和方法,將類的實現細節放在分離的指針訪問類中。
  用途:這種方法用於構造穩定的ABI的C++庫接口,減少編譯依賴
  
  現代C++不鼓勵使用原始指針 ,可以使用智能指針實現PIMPL

示例代碼

#include <iostream>
#include <memory>

class AppPrivate
{
public:
    AppPrivate() {}

    void print(std::string info) {
        std::cout << info << std::endl;
    }
};

class Application
{
public:
    Application(): d_ptr(new AppPrivate) {

    }

    void call_print(std::string info) {
        d_ptr->print(info);
    }

private:
    std::unique_ptr<AppPrivate> d_ptr;
};

int main(int argc, char *argv[])
{
    Application a;
    a.call_print("hello world");

    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章