开发者

Storing pointers to const objects in boost::ptr_unordered_map

开发者 https://www.devze.com 2023-03-05 15:08 出处:网络
I can\'t seem to make boost::ptr_unordered_map<uint32_t, const Foo> work - the underlying implementation looks like it\'s casting things to a void*.

I can't seem to make boost::ptr_unordered_map<uint32_t, const Foo> work - the underlying implementation looks like it's casting things to a void*.

Do I just have to bite the bullet and make my methods that wrap access to this do a const_cast<Foo*> when inserting items, or开发者_运维百科 is there something I'm missing here? Is there any way to store pointers to const objects (const Foo*)?


It looks like this isn't possible.

A workaround is to wrap access to ptr_unordered_map. The insert method should take a const auto_ptr and then do a const_cast<Foo*> to insert it.

If you hand back the auto_type to client code when removing elements, you'll need to unpack the pointer from that and transfer it into a const auto_ptr or similar to make ownership transfer explicit without leaking non-const references.

This is sufficient for my use case, as I don't need to expose any iterator behaviour - it's pure single-element insert/release/look-ups.

0

精彩评论

暂无评论...
验证码 换一张
取 消