I was surprised when the declaration:
const std::map<double, Foo*> myCollection;
would not allow me to call non-const methods on Foo*. I thought the const applied to the collection itself (i.e., no items could be added or removed). I would think the way to convey item const would be:
std::map<double, Foo const*> myCollection;
It seems the const in the first code snippet is distributive to the contents of the map instead of my assumption of applying only to the collection.
Am I missing something here? It seems counter-intuitive. How can I call non-const methods on the Foo* objects in the first declaration?
You must be doing something wrong —
operator[]onstd::mapis not declaredconst, so it cannot be used to access elements of the map. The reason it’s notconstis because if the key isn’t present in the map, it gets added to the map with a default-constructed value, and doing so modifies the map.Instead, use the
findmethod to get an iterator. The returned iterator cannot be used to modify the map, but it can be used to modify the objects which are pointed to by the values. For example, the following code compiles and outputs4: