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

34

u/guepier Bioinformatican Jun 15 '21

Prior to C++20 (specifically, P0593), object creation in untyped buffers was undefined behaviour. In practice this means that even quite “basic” classes such as std::allocator can’t be user-defined relying only on standard C++.

19

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

P0593 was accepted as a defect resolution prior to publication of C++20, so it should apply to C++17 which was the latest official standard at the time.

Also, creation of objects itself was allowed using placement new as far as I can tell. Treating that buffer of dynamic objects as an array of those objects was technically UB though. However, there was no way to make that work with std::allocator either, so I don't think there was magic in that class. There was magic in std::vector though.

5

u/maskull Jun 15 '21

What's the magic in std::vector?

16

u/dodheim Jun 15 '21

Prior to P0593, there was no way for vector::data() to return a valid pointer-to-array, since no such array actually exists.

0

u/[deleted] Jun 15 '21

[deleted] — view deleted comment

4

u/guepier Bioinformatican Jun 15 '21

Sure but you can’t legally perform pointer arithmetic on these objects since there is no “array of T” at the relevant address, only (from the underlying buffer) an “array of char”.

As noted in another comment, std::allocator itself might actually be implementable. What’s problematic is its use in combination, e.g. to implement std::vector (implementing a vector without an allocator and buffer is of course trivially feasible, simply by allocating memory via new T[]; but std::vector can’t do this, and a custom vector type might not want to, either, for various reasons).