C++中Pimpl的慣用法詳解
介紹
Pimpl(Pointer to Implementation)是一種常見的 C++ 設(shè)計模式,用于隱藏類的實現(xiàn)細(xì)節(jié),從而減少編譯依賴和提高編譯速度。本文將通過一個較為復(fù)雜的例子,展示如何使用智能指針(如 std::unique_ptr)來實現(xiàn) Pimpl 慣用法。
什么是 Pimpl 慣用法
Pimpl 是 “Pointer to Implementation” 的縮寫,這個模式可以幫助我們:
- 將接口和實現(xiàn)分離
- 減少頭文件中的依賴
- 加速編譯
基本實現(xiàn)
基本的 Pimpl 實現(xiàn)需要一個前置聲明的內(nèi)部類和一個指向該內(nèi)部類的指針。在這里,我們使用 std::unique_ptr 來管理這個內(nèi)部類的實例。
MyClass.h
#include <memory>
class MyClassImpl; // 前置聲明
class MyClass {
public:
MyClass();
~MyClass();
void DoSomething();
private:
std::unique_ptr<MyClassImpl> pimpl;
};MyClass.cpp
#include "MyClass.h"
class MyClassImpl {
public:
void DoSomething() {
// 實現(xiàn)細(xì)節(jié)
}
};
MyClass::MyClass() : pimpl(std::make_unique<MyClassImpl>()) {}
MyClass::~MyClass() = default;
void MyClass::DoSomething() {
pimpl->DoSomething();
}示例
假設(shè)我們有一個 Car 類,它有多個組件,如 Engine 和 Wheel。
Car.h
#include <memory>
class CarImpl;
class Car {
public:
Car();
~Car();
void Start();
void Stop();
private:
std::unique_ptr<CarImpl> pimpl;
};Car.cpp
#include "Car.h"
#include "Engine.h"
#include "Wheel.h"
class CarImpl {
public:
Engine engine;
Wheel wheel[4];
void Start() {
engine.Start();
// 其他邏輯
}
void Stop() {
engine.Stop();
// 其他邏輯
}
};
Car::Car() : pimpl(std::make_unique<CarImpl>()) {}
Car::~Car() = default;
void Car::Start() {
pimpl->Start();
}
void Car::Stop() {
pimpl->Stop();
}在這個例子中,Car 的用戶只需要包含 Car.h,而不需要知道 Engine 和 Wheel 的存在。這樣就降低了編譯依賴并提高了編譯速度。
總結(jié)
通過使用 Pimpl 慣用法和智能指針,我們能更有效地隱藏實現(xiàn)細(xì)節(jié),提高編譯速度,并使代碼更易于維護(hù)。
到此這篇關(guān)于C++中Pimpl的慣用法詳解的文章就介紹到這了,更多相關(guān)C++ Pimpl內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
c++ vector(向量)使用方法詳解(順序訪問vector的多種方式)
vector是向量類型,它可以容納許多類型的數(shù)據(jù),如若干個整數(shù),所以稱其為容器,本文介紹一下使用方法2013-12-12
C++ win系統(tǒng)如何用MinGW編譯Boost庫
這篇文章主要介紹了C++ win系統(tǒng)如何用MinGW編譯Boost庫問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12
VisualStudio2019構(gòu)建C/C++靜態(tài)庫和動態(tài)庫dll的問題 附源碼
這篇文章主要介紹了VisualStudio2019構(gòu)建C/C++靜態(tài)庫和動態(tài)庫(dll)(文末附源碼),本文通過實例圖文相結(jié)合給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03

