C++ std::any vs void*: Type-Erased Storage Done Safely

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

Aspectvoid*std::any
Type infoNoYes
Wrong castUBbad_any_cast
Lifetimemanualmanaged 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

  1. Prefer std::any over ad-hoc void* in C++ codebases
  2. void* at C boundaries

  • variant vs union
  • Type erasure

Keywords

std::any, void pointer, type erasure, any_cast