更多 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)