I have a simple question regarding const_cast
and best practices regarding STL containers. Consider the following where class Foo
has a private STL std::map
from Widget*
to int
:
Declaration:
#include <map>
using std::map;
class Widget;
class Foo {
public:
Foo(int n);
virtual ~Foo();
bool hasWidget(const Widget&);
private:
map<Widget*,int> widget_map;
};
Definition:
#include <map>
#include "Foo.h"
#include "Widget.h"
using std::map;
Foo::Foo(int n)
{
for (int i = 0; i < n; i++) {
widget_map[new Widget()] = 1;
}
}
Foo::~Foo()
{
map<Widget*, int>::iterator it;
for (it = widget_map.begin(); it != widget_map.end(); it++) {
delete it->first;
}
}
bool Foo::hasWidget(const Widget& w)
{
map<Widget*, int>::iterator it;
it = this->widget_map.find(const_cast<Widget*>(&w));
return ( ! ( it == widget_map.end() ) );
}
Given that hasWidget
takes a reference to const as its parameter, the constness needs to be cast away when calling map::find
(wiget_map
being from Wiget*
to int
). As far as I can tell, this approach is both sensible and desirable -- but I'm reluctant to accept it as such without feedback from more experienced C++ programmers.
It seems to me that this is one of the few cases of using const_cast
appropriately given that we're passing the result of the cast to an STL method. Am I correct?
I realise that other permutations of this question have been posed already (for example, const_cast for vector with object) but none seem to directly address the above.
Thanks in advance.