I have a simple question regarding const_castand best practices regarding STL containers. Consider the following, where the class Foohas a private STL std::mapfrom 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 it hasWidgettakes a reference to const as its parameter, constness must be discarded when called map::find( wiget_mapfrom Wiget*to int). As far as I can tell, this approach is reasonable and desirable, but I do not want 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 use, const_castrespectively, given that we pass the result of the cast to the STL method. Am I right?
, (, const_cast ), , -, .
.