简体   繁体   中英

C++ const correctness with std::pair

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

The interface claims to store std::pair<const X,Y> (ie that's what value_type is). Internally, however, the implementation stores a sorted array of std::pair<X,Y> .

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

Moving to storing an array of std::pair<const X,Y> wouldn't be possible, as the implementation needs to copy elements around in the array to implement insertion and deletion. One of the ways it does this is using std::sort .


Edit: Although I believe the reinterpret_cast invokes undefined behavior (or implementation defined?) I have yet to come across a compiler where this doesn't work - Am I worrying about nothing?


Current implementation of iterator's dereference:

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);
}

I believe you can't solve this by returning a std::pair . Instead, you're going to have to return a proxy object that looks like a standard pair, but if you update the second member it propagates through to the main container, while the first member is expose as const as you desire.

"Better alternative?" What is wrong with reinterpret_cast ? In this case, the cast is even well-defined since you're casting between objects with compatible (in fact, identical) representations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM