skip to content
Ivan's wiki
Site Tools
Search
Tools
Show pagesource
Backlinks
Recent Changes
Media Manager
Sitemap
>
Recent Changes
Media Manager
Sitemap
cpp-strict-aliasing
This page is read only. You can view the source, but not change it.
# C++ strict aliasing **[Strict aliasing](https://en.cppreference.com/w/cpp/language/object)** is a rule stating that accessing an object through a pointer or reference of a different type (that doesn't form a proper subset relationship, like `char*`) causes undefined behavior. The compiler assumes pointers of different types never point to the same object and optimizes accordingly. Violating this assumption produces incorrect results. Avoid strict aliasing violations: don't cast pointers between unrelated types to access objects; use `std::memcpy` or `std::bit_cast` (C++20) for type-punning. ## Example This example shows a strict aliasing violation and the safe alternative. ```cpp // compile: g++ -std=c++20 -O2 -o alias alias.cpp // run: ./alias // description: strict aliasing: incorrect casting vs safe bit_cast #include <iostream> #include <cstring> #include <bit> int main() { int x = 0x12345678; // Unsafe: violates strict aliasing // float* fp = (float*)&x; // float y = *fp; // UB: accessing int via float* // Safe: use std::bit_cast (C++20) float y = std::bit_cast<float>(x); std::cout << "Safely bit-casted: " << y << "\n"; // Safe: use memcpy float z; std::memcpy(&z, &x, sizeof(int)); std::cout << "Via memcpy: " << z << "\n"; return 0; } ```
Page Tools
Show pagesource
Backlinks
Back to top