C++ pimpl機制詳細講解

源碼倉庫

什麼是PImpl機制

Pointer to implementation(PImpl ),通過將類的實現細節放在一個單獨的類中,從其對象表示中刪除它們,通過一個不透明的指針訪問它們(cppreference 是這麼說的)

通過一個私有的成員指針,將指針所指向的類的內部實現數據進行隱藏

class Demo {
public:
	...
private:
	DemoImp* imp_;
}

為什麼用PImpl 機制

個人拙見

  • C++ 不像Java 後端型代碼,能有行業定式的列目錄名形成規范(controller、Dao等)
  • 隱藏實現,降低耦合性和分離接口(隱藏類的具體實現)
  • 通過編譯期的封裝(隱藏實現類的細節)

業界實現

優秀開源代碼有實現

PImpl實現

方法一

cook_cuisine.h

#pragma once
#include <unordered_map>
#include <vector>
#include <memory>
//  Pointer to impl ementation
class CookImpl;
// 後廚
class Cook {
public:
    Cook(int, const std::vector<std::string>&);
    ~Cook();
    std::vector<std::string> getMenu();     /* 獲取菜單 */
    uint32_t getChefNum();                  /* 獲取廚師數量 */
private:
    CookImpl* impl_;
};
typedef std::shared_ptr<Cook> CookPtr;		// 美妙的typedef 懶人工具

cook_cuisine.cc

#include "cook_cuisine.h"
class CookImpl {
public:
    CookImpl(uint32_t checf_num, const std::vector<std::string>& menu):checf_num_(checf_num), menu_(menu) {}
    std::vector<std::string> getMenu();
    uint32_t getChefNum();
private:
    uint32_t checf_num_;
    std::vector<std::string> menu_;
};
std::vector<std::string> CookImpl::getMenu() {
    return menu_;
}
uint32_t CookImpl::getChefNum() {
    return checf_num_;
}
Cook::Cook(int chef_num, const std::vector<std::string>& menu) {
    impl_ = new CookImpl(chef_num, menu);
}
Cook::~Cook() {
    delete impl_;
}
std::vector<std::string> Cook::getMenu() {
    return impl_->getMenu();
}
uint32_t Cook::getChefNum() {
    return impl_->getChefNum();
}

方法二

cook_cuisine.h

#pragma once
#include <unordered_map>
#include <vector>
#include <memory>
#include "cook_cuisine_imp.h"
// 後廚
class Cook {
public:
    Cook(int, const std::vector<std::string>&);
    ~Cook();
    std::vector<std::string> getMenu();     /* 獲取菜單 */
    uint32_t getChefNum();                  /* 獲取廚師數量 */
private:
    CookImplPtr impl_;
};
typedef std::shared_ptr<Cook> CookPtr;

cook_cuisine.cc

#include "cook_cuisine.h"
Cook::Cook(int chef_num, const std::vector<std::string>& menu) {
    impl_.reset(new CookImpl(chef_num, menu));
}
Cook::~Cook() {
}
std::vector<std::string> Cook::getMenu() {
    return impl_->getMenu();
}
uint32_t Cook::getChefNum() {
    return impl_->getChefNum();
}

cook_cuisine_imp.h

#pragma once
#include <vector>
#include <unordered_map>
#include <memory>
class CookImpl {
public:
    CookImpl(uint32_t checf_num, const std::vector<std::string>& menu):checf_num_(checf_num), menu_(menu) {}
    std::vector<std::string> getMenu();
    uint32_t getChefNum();
private:
    uint32_t checf_num_;
    std::vector<std::string> menu_;
};
typedef std::shared_ptr<CookImpl> CookImplPtr;

cook_cusine_imp.cc

#include "cook_cuisine_imp.h"
std::vector<std::string> CookImpl::getMenu() {
    return menu_;
}
uint32_t CookImpl::getChefNum() {
    return checf_num_;
}

main.cc

#include "cook_cuisine.h"
#include <iostream>
using namespace std;    // Testing, 平時開發可千萬別用這句
int main() {
    int checf_num = 10;
    const std::vector<std::string> menus = { "Chicken", "Beef", "Noodle", "Milk" };
    CookPtr cook(new Cook(checf_num, menus));
    auto cook_menu = cook->getMenu();
    auto cook_checf_num = cook->getChefNum();
    cout << "======================Chinese Cook======================\n";
    cout << "============Checf: " << cook_checf_num << " people\n";
    cout << "==========Menu\n";
    for (size_t i = 0; i < cook_menu.size(); i++) {
        cout << "============" << i + 1 << " : " << cook_menu[i] << "\n";
    }
    return 0;
}

CMakeLists.txt

mkdir build
cd build
cmake ..

PImpl 缺點

空間開銷:每個類都需要額外的指針內存指向實現類

時間開銷:每個類間接訪問實現的時候多一個間接指針操作的開銷

閱讀開銷:使用、閱讀和調試上帶來一些不便(不是啥問題)

總結

每種設計方法都有它的優點和缺點

PImpl 用一些內存空間和額外類的實現換取耦合性的下降,是可以接受的

但重點在:在性能/內存要求不敏感處,PImpl 技術才更優不錯的發揮舞臺

極端例子:

你不可能在斐波那契的實現中還加個PImpl 機制,多此一舉

到此這篇關於C++ pimpl機制詳細講解的文章就介紹到這瞭,更多相關C++ pimpl機制內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: