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

37

u/frrrwww Jun 15 '21

Not a class but I believe std::byte is magic because a pointer to it can alias other data types (same as char)

23

u/exarnk Jun 15 '21

I'm reasonably certain std::byte is just implemented as

enum class byte : uint8_t {};

With a bunch of functions. I felt that is quite clever and nice.

15

u/avdgrinten Jun 15 '21

It is not; that implementation is not legal. The list of allowed object access does not list "enum whose underlying type is unsigned char" as a valid type to access arbitrary objects (only unsigned char, char and std::byte are listed).

GCC and Clang introduced the [[gnu::may_alias]] attribute to implement std::byte.

4

u/exarnk Jun 15 '21

My C++20 draft states in [cstddef.syn] the following:

enum class byte : unsigned char {};

This seems to correspond with the current Git HEAD of libstdc++-v3 (line 69):

https://gcc.gnu.org/git/?p=gcc.git;a=blob;f=libstdc%2B%2B-v3/include/c_global/cstddef;h=13ef7f03c12584804e4dd1635954723f628addc0;hb=HEAD

What am I missing?

12

u/avdgrinten Jun 15 '21

See, for example, this LLVM commit: https://reviews.llvm.org/D35824

3

u/exarnk Jun 15 '21

Thanks, that made things a lot clearer for me.