STL std :: map, pass by ref to const and the need for const_casting

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 ), , -, .

.

+3
6

, " ", ...

const_cast, . - hasWidget const ref: ? , , , Widget . , Widget .

, Widget, true. ( , const):

bool hasWidget(const Widget *) const;
+1

map<const Widget*,int>? , , .

, , , , . , referand , const. - , , referand, const, referand ( const). , const , const , ...

Btw, hasWidget , count, find. ( ), , count, find const_cast , , count . , count. , .

+1

, const_cast<>. hasWidget const.

+1

hasWidget, Widget*? , , , . const, :

bool hasWidget(Widget *) const;
+1

, , - - . , , hasWidget , !

, Widget , , , std::map! :

std::map<Widget, int>

const_cast!

+1

. "", , , .

:

std::map<Widget::Id, Widget*>

Widget::Id int .

.

, Boost Pointer Container:

boost::ptr_map<Widget::Id, Widget>

.

+1

Source: https://habr.com/ru/post/1777632/


All Articles