Skip to content

Search topics & cppreference

Search all study topics, concept maps, and 6,587 C++ and C reference pages.

std::bit_cast

Separate raw memory allocation from object existence, master scope-bound RAII, and dodge dangling temporary traps.

Numerics
  • C++20
  • C++23
  • C++26
3 min readView on cppreference
NotebookLM
[basic.life][basic.stc][class.temporary][stmt.ranged]

Allocating bytes does not create an object, and freeing bytes is not what destroys one—lifetime begins at initialization and ends at destruction or storage reuse.

CppCon angle
Show the two timelines side by side: storage duration (how long the bytes exist) vs. object lifetime (when the typed object is legally alive inside those bytes).
Common audience trap
Assuming temporary lifetime extension propagates through accessor methods like auto& x = make_container().front(); inside range-for loops.
Stage takeaway
Use C++20 std::bit_cast instead of pointer-punning reinterpret_cast, and verify C++23 P2718 before trusting chained temporaries in range-for.

Storage duration is not object lifetime

[basic.life] §6.7.3

When you allocate raw aligned storage (alignas(Widget) std::byte buf[sizeof(Widget)];), storage exists, yet zero Widget objects live there. Accessing a Widget* pointing to buf before placement-new construction is Undefined Behavior.

C++20 softened one long-standing C interop pain point with Implicit-Lifetime Types ([intro.object]): malloc or std::start_lifetime_as (C++23) can implicitly begin the lifetime of trivial aggregates/arrays so C network buffers no longer rely on theoretical UB.

Why std::launder exists for const members
struct Node { const int id; };
Node* p = new Node{1};
// Reuse p's storage with placement new:
new (p) Node{2};
// Compiler may legally assume p->id is STILL 1 because 'id' is const!
int safe_id = std::launder(p)->id; // Guaranteed 2 ([ptr.launder])

Key rule: Compilers track pointer provenance and const member immutability; std::launder tells the optimizer a fresh object replaced the old one at that address.

Temporary lifetime extension & the range-for cliff

[class.temporary] & [stmt.ranged]

Writing const std::string& s = make_name(); extends the materialized temporary string to match s's scope. Write const char* p = make_name().c_str(); or auto& item : get_wrapper().items() in C++11–C++20, and the outer temporary wrapper is destroyed BEFORE the loop body even begins!

C++23 paper P2718R0 finally fixed range-based for loops by extending the lifetime of ALL temporaries in the range-initializer expression until the loop finishes—matching what every developer already assumed.

Pre-C++23 range-for dangling temporary
struct Wrapper { std::vector<int> items{1, 2, 3}; };
Wrapper make_wrapper();

// Pre-C++23: UB! Wrapper temporary dies before loop starts!
// C++23 (P2718R0): Well-defined! All temporaries in range-init extend across loop.
for (int v : make_wrapper().items) {
    use(v);
}

Key rule: Whenever a function returns a reference or view into a temporary receiver (std::string_view, std::span, or .items), check whether you are pre-C++23.

Across revisions (C++11 → C++17 → C++20 → C++23)

C++17

Introduced std::launder in <new> for placement-new over objects with const/reference members.

C++20

Introduced Implicit-Lifetime Types ([intro.object]) and std::bit_cast<To>(from) to eliminate strict-aliasing UB.

C++23

P2718R0 extended lifetime of all temporaries inside range-based for initializers; added std::start_lifetime_as.

Full 1:1 cppreference specification

Original specification mirrored from cppreference.com with restyled declaration panels and code windows.

Defined in header <bit>
template< class To, class From >
constexpr To bit_cast( const From& from ) noexcept;
(since C++20)

Obtain a value of type To by reinterpreting the object representation of From. Every bit in the value representation of the returned To object is equal to the corresponding bit in the object representation of from. The values of padding bits in the returned To object are unspecified.

If there is no value of type To corresponding to the value representation produced, the behavior is undefined. If there are multiple such values, which value is produced is unspecified.

A bit in the value representation of the result is indeterminate if it

  • does not correspond to a bit in the value representation of From (i.e. it corresponds to a padding bit), or
  • corresponds to a bit of an object that(until C++26)for which the smallest enclosing object(since C++26) is not within its lifetime, or
  • has an indeterminate value.

A bit in the value representation of the result is erroneous if it corresponds to a bit for which the smallest enclosing object has an erroneous value.

(since C++26)

The result does not otherwise contain any indeterminate or erroneous values.

For each bit in the value representation of the result that is indeterminate, the smallest object containing that bit has an indeterminate value; the behavior is undefined unless that object is of an uninitialized-friendly type.

The result does not otherwise contain any indeterminate values.

(until C++26)

For each bit b in the value representation of the result that is indeterminate or erroneous, let u be the smallest object enclosing b:

  • If u is of uninitialized-friendly type, u has an indeterminate value if any of the bits in its value representation are indeterminate, or otherwise has an erroneous value.
  • Otherwise, if b is indeterminate, the behavior is undefined.
  • Otherwise, the behavior is erroneous, and the result is as specified above.
(since C++26)

This overload participates in overload resolution only if sizeof(To) == sizeof(From) and both To and From are TriviallyCopyable types.

This function template is constexpr if and only if each of To, From and the types of all subobjects of To and From:

  • is not a union type;
  • is not a pointer type;
  • is not a pointer to member type;
  • is not a volatile-qualified type; and
  • has no non-static data member of reference type.

Parameters

from - the source of bits for the return value

Return value

An object of type To whose value representation is as described above.

Possible implementation

To implement std::bit_cast, ignoring the fact that it's constexpr, std::memcpy can be used, when it is needed, to interpret the object representation as one of another type:

snippet.cpp
template<class To, class From>
std::enable_if_t<
    sizeof(To) == sizeof(From) &&
    std::is_trivially_copyable_v<From> &&
    std::is_trivially_copyable_v<To>,
    To>
// constexpr support needs compiler magic
bit_cast(const From& src) noexcept
{
    static_assert(std::is_trivially_constructible_v<To>,
        "This implementation additionally requires "
        "destination type to be trivially constructible");
 
    To dst;
    std::memcpy(&dst, &src, sizeof(To));
    return dst;
}

Notes

reinterpret_cast (or equivalent explicit cast) between pointer or reference types shall not be used to reinterpret object representation in most cases because of the type aliasing rule.

Feature-test macro Value Std Feature
__cpp_lib_bit_cast 201806L (C++20) std::bit_cast

Example

example.cpp
#include <bit>
#include <cstdint>
#include <iostream>
 
constexpr double f64v = 19880124.0; 
constexpr auto u64v = std::bit_cast<std::uint64_t>(f64v);
static_assert(std::bit_cast<double>(u64v) == f64v); // round-trip
 
constexpr std::uint64_t u64v2 = 0x3fe9000000000000ull;
constexpr auto f64v2 = std::bit_cast<double>(u64v2);
static_assert(std::bit_cast<std::uint64_t>(f64v2) == u64v2); // round-trip
 
int main()
{
    std::cout
        << "std::bit_cast<std::uint64_t>(" << std::fixed << f64v << ") == 0x"
        << std::hex << u64v << '\n'
        << "std::bit_cast<double>(0x" << std::hex << u64v2 << ") == "
        << std::fixed << f64v2 << '\n';
}
Possible output
std::bit_cast<std::uint64_t>(19880124.000000) == 0x4172f58bc0000000
std::bit_cast<double>(0x3fe9000000000000) == 0.781250

Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
CWG 2482
(P1272R4)
C++20 it was unspecified whether UB would occur when involving indeterminate bits specified

See also

implicitly creates objects in given storage with the object representation reused
(function template)

Content from this page on cppreference.com, licensed under CC-BY-SA 3.0 and GFDL. Modified: restyled, site navigation removed, code windows added. Offline snapshot of 9 February 2025.