hn.today

Composite objects and C++26 the std:polymorphic type

mariusbancila.ro3 points0 comments
Screenshot of Composite objects and C++26 the std:polymorphic type

This explains how C++26’s std::polymorphic solves the common problem of owning polymorphic components inside value-type composites. Using a familiar example - an Event hierarchy (TemperatureReadingEvent, SmokeDetectedEvent, CarbonMonoxideDetectedEvent) stored in an EventLog - shows the drawbacks of the traditional approaches: storing base objects causes slicing, unique_ptr preserves dynamic type but makes the owner non-copyable, variant forces a closed set, and adding a virtual clone() pushes boilerplate, leaks infrastructure into the public API, fails const-propagation, and allows nulls. An EventLog implemented with unique_ptr requires hand-written copy/assignment (Rule of Five) to clone every element, which is error-prone and verbose.

std::polymorphic replaces the clone pattern by type-erasing the copy and destroy operations at construction time, much like std::function/std::any erase callables. Constructing with std::in_place_type captures how to copy and destroy the concrete derived type; later copies invoke that stored operation, restoring value semantics without requiring virtual clone() or manual special members. The type provides operator* and operator-> with const-propagation, is never null except when moved-from (valueless_after_move()), is allocator-aware, and may use a small-buffer optimization. It does not expose the concrete stored type (no type() query); if you need it, dynamic_cast on the contained reference is the intended approach.

Read on mariusbancila.ro0 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Programming

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.