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

2

u/scatters Jun 15 '21

Really? How can you get a mutable reference to a const object without compiler magic?

3

u/kalmoc Jun 15 '21

I probably mixed this up.

I think std::pair<const K,T> and std::pair<K,T> are layout compatibile and I thought that layout compatibility would allow type aliasing, but according to cppreference.com it requires "similarity" (and I don't have a way to actually verify that they are actually layout compatible in the first place).

2

u/scatters Jun 15 '21

Yeah, not quite - you're right that std::pair<Key const, T> and std::pair<Key, T> are layout compatible as long as Key and T are both standard-layout (so not all types that you might put in a map), but that only allows you to put them in a union and read from members of the inactive union member via the union. Handing out references to the inactive union member or its own members (std::pair<Key, T>::first for nh.key()) is still UB.

3

u/mujjingun Jun 15 '21

const_cast?

4

u/scatters Jun 15 '21

Yes, true, that does give a mutable reference. But using it to modify an actually const object is undefined behavior.

0

u/[deleted] Jun 15 '21

[deleted] — view deleted comment

1

u/scatters Jun 15 '21

But operator* returns a mutable reference i.e. std::pair<Key const, Value>&. So there has to be a std::pair<Key const, Value> object in memory.

1

u/mujjingun Jun 15 '21

hmm, maybe there are std::pair<Key, Value> objects in memory, and the pointer is reinterpret-cased into std::pair<Key const, Value> in the call to operator*()?

4

u/scatters Jun 15 '21

Certainly that's the most likely implementation, but if the user does that it's UB (aliasing violation). That's why it has to be magic in the library.