r/cpp • • 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

140 comments sorted by

View all comments

1

u/OldWolf2 Jun 15 '21

std::initializer_list because it is created anywhere with {}

It is only created in a few specific contexts with {}, not "anywhere". The only one I can think of right now is:

  • auto x = { 1, 2, 3 };

For classes with initializer_list constructor there's no magic involved, the parameter is initialized by the braced list (the braced list does not have a type).

3

u/SirClueless Jun 15 '21

That still qualifies as magic. You can't define your own class that will be initialized from a braced-init-list when it's the parameter of a constructor.

1

u/RicardoRedstone Jun 16 '21

You can also intialize it the same way if you use a variadic template, but it won't be pretty to work with, uses a ton of stack space and generates a LOT of code.

https://godbolt.org/z/Tb9T61v6d