const_cast
我有一个关于 STL 容器的简单问题和最佳实践。考虑以下,其中类Foo
有一个私有 STL std::map
from Widget*
to int
:
宣言:
#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;
};
定义:
#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() ) );
}
鉴于hasWidget
将引用 const 作为其参数,因此在调用时需要丢弃 const map::find
(wiget_map
从Wiget*
to int
)。据我所知,这种方法既明智又可取——但如果没有更有经验的 C++ 程序员的反馈,我不愿意接受它。
在我看来,这是为数不多的const_cast
适当使用的案例之一,因为我们将强制转换的结果传递给 STL 方法。我对么?
我意识到这个问题的其他排列已经提出(例如,const_cast for vector with object)但似乎没有一个直接解决上述问题。
提前致谢。