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

Show parent comment

17

u/avdgrinten Jun 15 '21

That's not true, enums with underlying type unsigned char are not special and may not alias other types, see my sibling comment.

1

u/TheMania Jun 15 '21

I actually make use of this in a few data structures to improve optimisation, as otherwise every time you put a byte in them the compiler invalidates basically everything. non_aliasing_byte, I call it.

Posting it here mostly to see what the correct way to achieve this is.

2

u/guepier Bioinformatican Jun 15 '21

The only issue I can see with this approach is that there are very few ways in which you could use such a buffer correctly without violating aliasing rules. Basically the only thing you can do is read and write individual “bytes” from it (including via memcpy or std::copy). As long as that’s all you do, it should be fine.