c++boost-ptr-container

Storing pointers to const objects in boost::ptr_unordered_map


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*)?


Solution

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