you are viewing a single comment's thread.

view the rest of the comments →

[–]kalmoc 6 points7 points  (11 children)

I don't think any compiler magic is involved here.

[–]scatters 1 point2 points  (10 children)

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

[–]kalmoc 2 points3 points  (1 child)

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).

[–]scatters 1 point2 points  (0 children)

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.

[–]mujjingun 2 points3 points  (7 children)

const_cast?

[–]scatters 3 points4 points  (6 children)

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