Type punning refers to techniques that allow accessing an object as a different type by taking advantage of the memory layout. This allows bypassing the strict aliasing rules in C++. Here's an explanation of how it works and some common use cases.
Type punning involves leveraging the fact that the memory layout of some types may match, even if they are considered different types by the compiler. Some examples:
int
and a float
may both occupy 4 bytes.struct
with exactly one int
member will match the layout of just an int
.This allows code to reinterpret the binary representation of the same memory as different types.
Some methods of type punning include:
union Data {
int i;
float f;
};
Data data;
data.i = 10;
// Now access the same memory as a float
std::cout << data.f;
// Using memcpy
int x = 10;
float f;
memcpy(&f, &x, sizeof(int)); // Copy int bits to float
// Using reinterpret_cast
int y = 10;
float g = reinterpret_cast<float&>(y);
#include <iostream>
int main() {
// Normal integer variable
int x = 10;
// Type pun to float using reinterpret_cast
float f = reinterpret_cast<float&>(x);
// Print out floating point representation
std::cout << f << std::endl; // 10.0
// Modify as float
f = 15.5f;
// Print out new integer representation
std::cout << x << std::endl; // 1082130432 (bits now represent 15.5)
return 0;
}
struct Entity{
int x,y;
int* getPositions(){
return &x;
}
};
int main(){
Entity e = {5, 8};
int* position = e.getPositions();
cout << position[0] << ',' << position[1] << endl; // i just accessed the struct in
// the format of an array without copying it and making the code slow.
int y = *(int*)((char*)&e + 4)
}
Type punning is commonly used for situations like:
It avoids having to manually copy or convert between types in some performance-critical code.
Pros:
Cons:
When using type punning:
Like any advanced technique, type punning should be used intentionally rather than as a "shortcut" for type safety. When applied correctly in suitable use cases, it can be a valuable optimization. But misuse can easily lead to bugs!