Skip to main content

  | मौसम…

411 समाचार
Public archive edition · Attributed source reporting with original dates · AI drafts are excluded

411 REFERENCE · Wikibooks

More C++ Idioms/Fast Pimpl

Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.

Intent Increase performance of Handle Body idiom. Also Known As Motivation Regular PIMPL idiom achieves "Compilation Firewall" by sacrificing performance. Fast PIMPL attempts to reduce the overhead of heap allocation and non-local memory access by composing the implementation object within the original interface object. Solution and Sample Code // Wrapper.hpp struct Wrapper { Wrapper(); ~Wrapper(); // deprecated in C++23 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(); }Note that handle to instance of Wrapped class is not required. To reduce memory footprint Wrapped class can be accessed by a helper function instead .static Wrapper::Wrapped* get_wrapped(Wrapper* wrapper) { // c++17 compatible return std::launder(reinterpret_cast<Wrapper::Wrapped*>(&wrapper->storage)); } Known Uses This pattern is frequently used in high performance or memory constrained environments when implementation is desired to be unseen or decoupled. Related Idioms Handle Body (aka pimpl) References The Fast Pimpl Idiom