跳轉到內容

更多 C++ 慣用法/快速 Pimpl

來自華夏公益教科書,開放的書籍,開放的世界

提高控制代碼體慣用法的效能。

也稱為

[編輯 | 編輯原始碼]

常規 PIMPL 慣用法透過犧牲效能來實現“編譯防火牆”。快速 PIMPL 試圖透過在原始介面物件中組合實現物件來減少堆分配和非本地記憶體訪問的開銷。

解決方案和示例程式碼

[編輯 | 編輯原始碼]
// Wrapper.hpp
struct Wrapper {
    Wrapper();
    ~Wrapper();

    std::aligned_storage_t<32, alignof(std::max_align_t)> storage;
    
    struct Wrapped; // forward declaration
    Wrapped* handle;
};
// Wrapper.cpp
struct Wrapper::Wrapped {
};

Wrapper::Wrapper() {
    static_assert(sizeof(Wrapped) <= sizeof(this->storage) , "Object can't fit into local storage");
    this->handle = new (&this->storage) Wrapped();
}

Wrapper::~Wrapper() {
    handle->~Wrapped();
}

請注意,不需要對 Wrapped 類的例項進行控制代碼處理。為了減少記憶體佔用,可以透過輔助函式訪問 Wrapped 類。

static Wrapper::Wrapped* get_wrapped(Wrapper* wrapper) {
    // c++17 compatible
    return std::launder(reinterpret_cast<Wrapper::Wrapped*>(&wrapper->storage));
}

已知用途

[編輯 | 編輯原始碼]

當需要實現不可見或解耦時,這種模式經常用於高效能或記憶體受限的環境中。

[編輯 | 編輯原始碼]

參考文獻

[編輯 | 編輯原始碼]

快速 Pimpl 慣用法

華夏公益教科書