skip to content

In C++17, what can a std::any hold, and how does std::any_cast behave when the requested type does not exactly match?

level: middleimportance: should knowfreq 32%

answer

  1. copyable types only
  2. exact type, no conversions
  3. string literals decay
  4. pointer form versus value form

basics

~20 s

std::any holds one value of any copy-constructible type. std::any_cast<T> must name the exact stored type: the value form throws std::bad_any_cast on a mismatch, and the pointer form any_cast<T>(&a) returns nullptr. No conversions apply, so int is not long.

solid answer

~40 s

`std::any` (C++17, `<any>`) type-erases a single value of **any copy-constructible type**; a move-only type such as `std::unique_ptr<int>` is rejected at compile time. Reading requires naming the **exact** type stored: `std::any_cast<int>(a)` works for a stored `int`, but `std::any_cast<long>(a)` throws `std::bad_any_cast` (which derives from `std::bad_cast`) because no conversion is attempted. The pointer form, `std::any_cast<int>(&a)`, returns `nullptr` on a mismatch instead of throwing. A classic surprise: `a = "text";` stores a `const char*`, not a `std::string`. `a.type()` returns the `std::type_info` of the stored type, `has_value()` and `reset()` manage emptiness. Small values may live inside the object: the standard encourages that, permits it only for nothrow-movable types, and leaves the buffer size to the implementation.

code

cpp · 23 lines
cpp
#include <any>
#include <iostream>
#include <string>

int main() {
    std::any slot = 42;                                  // holds int
    std::cout << std::any_cast<int>(slot) << '\n';
    try {
        (void)std::any_cast<long>(slot);                 // exact type only: int is not long
    } catch (const std::bad_any_cast&) {
        std::cout << "any_cast<long> threw std::bad_any_cast\n";
    }

    slot = "text";                                       // decays: holds const char*
    std::cout << std::boolalpha
              << (std::any_cast<std::string>(&slot) == nullptr) << ' '
              << (slot.type() == typeid(const char*)) << '\n';

    slot = std::string("text");
    if (auto* s = std::any_cast<std::string>(&slot)) std::cout << s->size() << '\n';
    slot.reset();
    std::cout << slot.has_value() << '\n';
}

go deeper

for a junior

Know that std::any holds one value of any copyable type and that std::any_cast<T> must name the stored type exactly or it throws std::bad_any_cast.

for a middle

Explain decay on storage (const char* for literals), the pointer form returning nullptr, the copy-constructible requirement, and why small values may avoid allocation.

for a senior

Argue why std::variant or a template is usually better, where any is justified at a plugin or framework boundary, and how to keep the exact-type knowledge in one place.

for a principal

Set a rule that limits std::any to boundaries where the stored type is genuinely unknown to the container, so type safety is not traded away by default.

## What std::any is `std::any` (C++17, header `<any>`) is a **type-erased container for one value** of any copy-constructible type. Unlike `std::variant`, its set of possible types is not listed anywhere; the type is recorded at run time and checked when you read. It suits places where a framework must carry a value it does not understand, such as a user-data slot on a UI widget or a property bag keyed by name, and almost nowhere else. ## What it can hold - Any type `T` whose decayed type is **copy constructible**. The constructors are constrained on `is_copy_constructible_v`, because copying an `any` must copy the hidden value. `std::any a = std::make_unique<int>(1);` fails to compile; clang reports `no viable conversion from 'unique_ptr<int>' to 'std::any'`. - Values are stored after **decay**: arrays become pointers and functions become function pointers. So `a = "text";` stores a `const char*`, and `std::any_cast<std::string>(&a)` returns `nullptr`. - Nothing at all: a default-constructed `any` is empty, `has_value()` returns `false`, and `type()` returns `typeid(void)`. ## Reading it back with any_cast | Form | Exact match | Mismatch or empty | |---|---|---| | `std::any_cast<T>(a)` (value or reference) | the value, or a reference for `T&` | throws `std::bad_any_cast` | | `std::any_cast<T>(&a)` (pointer) | pointer to the stored object | `nullptr` | Key rules from the draft: 1. The value form throws if `a.type() != typeid(remove_reference_t<T>)`; the pointer form returns non-null only if `type() == typeid(T)`. **Exact** means exact: a stored `int` is not readable as `long`, `unsigned` or `double`, and a stored `Derived` is not readable as `Base`. 2. `std::any_cast<int&>(a) = 10;` writes into the stored value; `std::any_cast<int>(a)` returns a copy. 3. Casting away `const` is rejected: from a `const std::any`, `any_cast<std::string&>` is ill-formed and you must ask for `const std::string&`. 4. `std::bad_any_cast` derives from `std::bad_cast`, so a handler for `std::bad_cast` catches it too. ## Storage and cost The draft says implementations **should** avoid dynamic allocation for small contained values, but may apply that small-object optimization only to types whose move constructor is `noexcept`. Buffer size is each library's choice: - libc++ keeps values up to three pointers in size (24 bytes on 64-bit) inside the object, with pointer alignment; - libstdc++ keeps values up to one pointer in size inside the object; - anything larger, over-aligned or not nothrow-movable goes on the heap. Every `any_cast` compares `std::type_info` objects, and every copy goes through a type-erased function. That makes `std::any` noticeably more expensive than a `std::variant`, which knows its alternatives at compile time. ## Building values in place Besides assignment, `std::any` offers in-place construction, useful for types that are expensive to move: - `std::make_any<Widget>(args...)` returns an `any` holding a `Widget` built from `args`; - `std::any a(std::in_place_type<Widget>, args...)` does the same through a constructor; - `a.emplace<Widget>(args...)` destroys any current value and constructs a new one. All three still require the type to be copy constructible, because the `any` itself must remain copyable. ## When to use it, and when not - **Prefer `std::variant`** whenever you can list the types; you get compile-time exhaustiveness and in-place storage. - **Prefer a template or a concrete type** when the type is known at the call site. - **Use `std::any`** at a boundary where the type is chosen by code you do not control and only that code reads it back, such as a plugin storing its own state in a host object. - **Wrap access** in one place that knows the type, so the exact-type rule is maintained by one function rather than every caller. A common interview probe is the literal trap: storing `"text"` and then failing to read a `std::string`. The fix is `a = std::string("text");`, or `using namespace std::string_literals;` and `a = "text"s;`.

  • Why can't std::any hold a std::unique_ptr, and what can you do instead?
    Copying a `std::any` must copy its contained value, so the constructors require a copy-constructible type, and `std::unique_ptr` is move-only. Store a `std::shared_ptr` if shared ownership is acceptable, keep the owner elsewhere and store a raw observer, or replace the `any` with a `std::variant` or a dedicated type-erased wrapper that supports move-only types.
  • Does storing an int in std::any allocate memory?
    Not on the major libraries: the draft encourages a small-object optimization for nothrow-movable types, and both libc++ and libstdc++ keep an `int` inside the `any` object itself. The size limit is implementation-specific (three pointers in libc++, one in libstdc++), so a larger type may allocate on one library and not the other.

  • std::any_cast<long> can read a stored int because the conversion is implicit
  • Assigning a string literal to std::any stores a std::string
  • std::any can hold any type, including move-only ones like unique_ptr
  • The pointer form of any_cast throws std::bad_any_cast on a mismatch
  • std::any never allocates because the standard guarantees a small buffer