[英]C++ const correctness with std::pair
I am maintaining a container class with an interface similar to std::map
/ std::unordered_map
. 我维护一个容器类,其接口类似于
std::map
/ std::unordered_map
。
The interface claims to store std::pair<const X,Y>
(ie that's what value_type
is). 接口声称存储
std::pair<const X,Y>
(即value_type
是什么)。 Internally, however, the implementation stores a sorted array of std::pair<X,Y>
. 但是,在内部,实现存储了
std::pair<X,Y>
的排序数组。
The current implementation uses reinterpret_cast
to implement the iterators. 当前实现使用
reinterpret_cast
来实现迭代器。 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. 转向存储
std::pair<const X,Y>
数组是不可能的,因为实现需要复制数组中的元素以实现插入和删除。 One of the ways it does this is using std::sort
. 其中一种方法是使用
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? 编辑:虽然我相信
reinterpret_cast
调用未定义的行为(或实现定义?)我还没有遇到一个编译器,这不起作用 - 我不担心什么?
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
. 我相信你不能通过返回一个
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. 相反,您将不得不返回看起来像标准对的代理对象,但如果更新
second
成员,它会传播到主容器,而第一个成员则根据需要公开为const
。
"Better alternative?" “更好的选择?” What is wrong with
reinterpret_cast
? reinterpret_cast
什么问题? In this case, the cast is even well-defined since you're casting between objects with compatible (in fact, identical) representations. 在这种情况下,由于您在具有兼容(实际上是相同)表示的对象之间进行转换,因此转换甚至是明确定义的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.