# C++26 新特性 std::polymorphic 详解

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

> Hacker News story 50148845 · language: zh · submitted 2026-10-19
> Web version: https://zeli.app/zh/story/50148845
> About this feed: https://zeli.app/llms.txt · Agent guide: https://zeli.app/skill.md

▲ 46 · by [jandeboevrie](<https://news.ycombinator.com/user?id=jandeboevrie>) · 💬 33
[original](<https://mariusbancila.ro/blog/2026/10/18/composite-objects-and-cpp26-the-stdpolymorphic-type/>) · [HN discussion](<https://news.ycombinator.com/item?id=50148845>)

## Summary

在 C++26 中，std::polymorphic 类型解决了复合对象实现多态时的长期痛点。过去，若要让拥有组件的类保持可复制性，开发者不得不手动实现 clone() 函数，导致代码冗余且容易出错。std::polymorphic 通过类型擦除技术，在构造时自动捕获复制逻辑，让复合对象天然支持深拷贝、const 传播且永不空悬。它让 EventLog 等类无需遵循 Rule of Five，回归 Rule of Zero，同时保留运行时多态能力。无论是策略模式、事件日志还是表达式树，这一新类型都让价值语义与多态完美融合，彻底告别手写的克隆样板代码。

## Key quote

> std::polymorphic 让组件像普通成员一样可复制、深度 const 且始终存在，同时保留其动态类型。

## HN discussion (33 comments)

### [quietbritishjim](<https://news.ycombinator.com/item?id=50177419>)

> 我顺着开头的链接读了那篇关于 std::indirect<T> 的文章，据说可以用它来替代 std::unique_ptr<T> 实现 pImpl 惯用法：[1]
>
> \> 永不空：除了移动后的状态外，它始终持有值（但提供了一个名为 valueless_after_move() 的成员函数来检查状态）
>
> 唉，真是乱成一团。用这个替代 unique_ptr 的初衷，不就是为了避免这种陷阱吗？这里根本不可能实现安全的移动构造函数：要么得重新初始化被移动的对象，要么就得逐个元素移动（比如 `MyClass(MyClass&& other): impl(std::in_place, *other.impl) {}`），但这都会导致移动构造函数无法标记为 noexcept。如果当初直接把 indirect 的移动构造函数删掉，那会实用得多，毕竟过去大家用基于 pImpl 的类时通常就是这么做的。
>
> [1] https://mariusbancila.ro/blog/2026/07/23/the-pimpl-idiom-and...

### [nananana9](<https://news.ycombinator.com/item?id=50177325>)

> 这事儿我们做了 50 年了，你的事件结构体根本不需要类层次结构。
>
> enum EventType {
>
> EVENT_NONE,
>
> EVENT_TEMPERATURE_READING,
>
> EVENT_SMOKE_DETECTED,
>
> EVENT_CARBON_MONOXIDE_DETECTED,
>
> };
>
> struct Event {
>
> EventType type;
>
> union {
>
> TemperatureDeadingData temperature_reading;
>
> SmokeDetectedData smoke_detected;
>
> CarbonMonoxideDetected carbon_monoxide_detected
>
> } data;
>
> };
>
> std::vector<Event> events;

### [usrnm](<https://news.ycombinator.com/item?id=50177136>)

> 15 年前，读到 C++ 即将迎来所有这些酷炫新特性，我会很高兴；如今，我高兴的是自己不再使用它，也无需重新学习一切。我是不是老了？

---

## Cite

- Page: https://zeli.app/zh/story/50148845
- Date: 2026-10-19
- Source: mariusbancila.ro (https://mariusbancila.ro/blog/2026/10/18/composite-objects-and-cpp26-the-stdpolymorphic-type/)
- Hacker News: https://news.ycombinator.com/item?id=50148845

## Other languages

- en: https://zeli.app/story/50148845 · markdown: https://zeli.app/story/50148845.md
- ja: https://zeli.app/ja/story/50148845 · markdown: https://zeli.app/ja/story/50148845.md
- ko: https://zeli.app/ko/story/50148845 · markdown: https://zeli.app/ko/story/50148845.md
- de: https://zeli.app/de/story/50148845 · markdown: https://zeli.app/de/story/50148845.md
- es: https://zeli.app/es/story/50148845 · markdown: https://zeli.app/es/story/50148845.md
- ru: https://zeli.app/ru/story/50148845 · markdown: https://zeli.app/ru/story/50148845.md
