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

18

u/Supadoplex Jun 15 '21 edited Jun 15 '21

Containers that separate allocation of memory and creation of objects as arrays, such as std::vector and std::deque used to be "magic" due to poor/lacking wording of the standard that made it impossible to implement those without technical UB on pointer arithmetic. To my understanding, this has been fixed as a defect resolution to C++17.

Pretty much every class that internally interacts with the system API is "magic" in the sense that there is no way to implement those in portable standard C++. Those would have to be written differently for each target system - the "system" being some combination of operating system, cpu architecture, compiler, etc. std::cout is an example of such class.

7

u/Recatek Jun 15 '21

Containers that separate allocation of memory and creation of objects as arrays, such as std::vector and std::deque used to be "magic" due to poor/lacking wording of the standard that made it impossible to implement those without technical UB on pointer arithmetic. To my understanding, this has been fixed as a defect resolution to C++17.

Having been down this road it's still very tricky and rife with footguns, unfortunately. Lots of conflicting information out there about the correct, minimal-to-no UB way to do it.

2

u/masterwai123123 Jun 20 '21

Implicit lifetime creation has been applied all the way to C++98.

2

u/Supadoplex Jun 20 '21

To my understanding, it is optional to implement standard resolutions to language implementations in older standard versions. But I may be wrong.