C ++ const correctness with std :: pair

I maintain a container class with an interface similar to std::map / std::unordered_map .

The interface claims that it stores std::pair<const X,Y> (i.e. that value_type ). However, in the internal implementation, the implementation saves the sorted array std::pair<X,Y> .

The current implementation uses reinterpret_cast to implement iterators. My question is, is there a better alternative?

Moving to std::pair<const X,Y> to store the array would be impossible, since for implementation it is necessary to copy the elements in the array to implement insertion and deletion. One way this is done is to use std::sort .


Edit: Although I believe that reinterpret_cast causes undefined behavior (or a specific implementation?), I have yet to meet a compiler where this does not work - am I worried about anything?


Current implementation of iterator dereferencing:

 template <class K, class M> std::pair<const K,M>& operator*() { std::pair<K,M>& result = ...; return *reinterpret_cast<std::pair<const K,M>*)(&result); } 
+4
source share
2 answers

I believe that you cannot solve this by returning std::pair . Instead, you will have to return a proxy object that looks like a standard pair, but if you update the second member, it will be passed to the main container, while the first member will be shown as const as you wish.

+2
source

"The best alternative?" What is wrong with reinterpret_cast ? In this case, the casting will even be clearly defined, since you are throwing objects with compatible (in fact, identical) representations.

+1
source

Source: https://habr.com/ru/post/1389517/


All Articles