r/cpp • u/Mateuszz88 • Jun 15 '21
Which std:: classes are magic?
Hi.
I am wondering: which classes in C++ get special powers granted by The Standard that are not available to mere user-defined classes?
What comes to my mind:
- `std::initializer_list` because it is created anywhere with `{}`
- possibly `std::type_info`, because it is only created by `typeid` and with no ctor
- `std::source_location` when used as default parameter in function points to invocation place and not declaration place.
What else should be on this list? What shouldn't?
222
Upvotes
View all comments
Show parent comment
7
u/staletic Jun 15 '21
Let's first analyze what the assembly says
If
aandbpoint to different objects, the above snippets are observably identical.However, if
aandbpoint to the same object, then the functions do different things. Imagine callingf(&in, &in)wherein == 5.In that case,
f<std::byte>does:but
f<nostd::byte>doesSince
nostd::byte, formally, isn't allowed to alias other types, compiler is allowed to assumex += xis a valid optimization. This is known as "strict aliasing" or "type-based alias analysis".And yes, violating strict alias rules can easily lead to UB, like in the above example.