C++ std::any vs void*: Type-Erased Storage Done Safely
이 글의 핵심
std::any vs void*: when type safety matters, casting risks, and migration from legacy void* APIs.
For dynamic typing in a high-level language (contrast with C++ any/void*), see Python data types.
Introduction: “Store anything”
void* erases types completely. std::any keeps runtime type info and correct destruction.
This article covers:
- Safety
- Casting rules (
any_cast) - Performance
Comparison
| Aspect | void* | std::any |
|---|---|---|
| Type info | No | Yes |
| Wrong cast | UB | bad_any_cast |
| Lifetime | manual | managed for contained object |
Type safety
Prefer std::any for heterogeneous storage in modern code; reserve void* for C APIs.
Performance
any may allocate for large objects depending on library SBO policy—profile hot paths.
Summary
- Prefer
std::anyover ad-hocvoid*in C++ codebases void*at C boundaries
Related reading
- variant vs union
- Type erasure
Keywords
std::any, void pointer, type erasure, any_cast
Related posts
- Browse the C++ series
- C++ Adapter Pattern