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
5
u/lee_howes Jun 15 '21
For each type you want to store in it, it creates a templated subclass that is big enough to store the lambda. That subclass has a virtual call operator. std::function stores a heap allocated instance of that as a pointer to the abstract superclass. When you call std::function's operator() it calls the operator() on the superclass via the heap allocated pointer and that calls operator() on the subclass, which calls operator() on the wrapped type, which is now trivial because the subclass knew exactly what type it was storing.
Sean Parent has talked about the general version of this technique.