STL コンテナーに関する簡単な質問const_cast
とベスト プラクティスがあります。classFoo
にプライベート 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() ) );
}
が const への参照をパラメーターとして受け取ることを考えるとhasWidget
、呼び出し時に constness をキャストする必要がありますmap::find
( wiget_map
from Wiget*
to int
)。私が知る限り、このアプローチは賢明で望ましいものですが、経験豊富な C++ プログラマーからのフィードバックがなければ、このアプローチを受け入れるのは気が進まないのです。
const_cast
キャストの結果を STL メソッドに渡すことを考えると、これは適切に使用できる数少ないケースの 1 つに思えます。私は正しいですか?
この質問の他の順列がすでに提起されていることを認識しています(たとえば、object を使用した vector の const_cast)が、上記に直接対処しているようには見えません。
前もって感謝します。