insert or update in ptr_map

2019-08-14 09:18发布

问题:

The insert method of ptr_map does not update data if a key exists. So we need to use replace:

boost ptr_map replacing the value

Does ptr_map have a way of insertOrUpdate?

1) if a key does not exist, calls insert
2) if it exists, call replace

I guess this is how std::map insert works.

ptr_map has a [] operator. But it returns reference? I am not sure if it is safe to use it for doing the above.

Thank you,

回答1:

I guess this is how std::map insert works

No. In fact, std::map::insert looks up a matching key and returns the iterator to the existing element, if found. It does not replace. (You maybe confused with operator[] which returns a lvalue reference to a new/existing element).

ptr_map has a [] operator. But it returns reference? I am not sure if it is safe to use it for doing the above.

Of course you can. However, you should not assign to the reference if your element type is polymorphic. (Arguably, polymorphic value types are a key use case for Boost Pointer Containers). Because if you do you might end up with Object Slicing (What is object slicing?).

If you truly want to replace the object (managed pointer) with /another object/ use ptr_map::replace. If you need to just update the object that is already in the map, feel free to use operator[].



标签: c++ boost