C++26 标准新增了 std::indirect 词汇类型,定义在 <memory> 头文件中,旨在简化和改进传统的 PImpl(指向实现的指针)编程模式 [1]。
std::indirect 提供了三项关键特性 [1]。首先是深度复制,确保对象在复制时创建独立副本;其次是常量传播,使 const 限定符能正确应用于内部实现;第三是永不为空的保证,除了对象移动后的特定状态外 [1]。为了检查对象在移动后是否处于无效状态,开发者可以调用 valueless_after_move() 函数 [1]。
与使用原始指针或 std::unique_ptr 的实现方式相比,std::indirect 提供了更加简洁和安全的 PImpl 实现。使用 std::indirect 时需要注意,五个特殊成员函数必须在源文件中默认化,因为 Impl 类型在头文件中定义不完整 [1]。
截至目前,仅 GCC 16 版本支持 std::indirect [1]。此外,std::indirect 可与 std::polymorphic 配套使用以满足更复杂的场景需求 [1]。
C++26 introduces a new vocabulary type called std::indirect, defined in the <memory> header, designed to simplify the PImpl (Pointer to Implementation) programming pattern. [1] This type offers three key capabilities: deep copying, const propagation, and a guarantee that objects remain non-null except in the move-from state. [1]
The std::indirect type streamlines PImpl implementations compared to traditional approaches using raw pointers or std::unique_ptr. [1] When working with std::indirect, the five special member functions must be defaulted in the source file rather than the header, as the Impl class type remains incomplete in the header file. [1] Additionally, the valueless_after_move() function allows developers to check whether an object has entered an invalid state following a move operation. [1]
At the time of writing, only GCC 16 provides support for std::indirect. [1] The type also works in conjunction with std::polymorphic for polymorphic use cases. [1]