How to set a map of pointers as a map of pointers const?

I have a class with std :: map pointers as a member. Now I would like to open this element for reading only: modification is not allowed either for the map or for the objects that it points to. Internally, I need these pointers non-const, and I want to show them as const.

I have a solution that compiles at least, but I would like to know if there are any hidden issues that I will run into.

class A
{
public:
  const std::map<int, const float*>& GetMap() const { return *(reinterpret_cast< const std::map<int, const float*>* >( &m_Map)); }

private:
  std::map<int, float*> m_Map;
};

There is a possible problem that I can think of: if the internal layout of std :: map is different for pointer maps and const pointer maps, this will lead to ugly errors. But I cannot come up with reasonable reasons why this is so. Does anyone have an idea?

To clarify: I know that this is a hack, and there are more secure solutions (for example, separate access functions). I'm just wondering if this will succeed right away because of some piece of information that I lack.

+5
source share
4 answers

This, of course, is undefined behavior (EDIT: it looks like it's actually only unspecified) because the two cards (from the language point of view) are completely unrelated types. It may work now, but someday it will break and cause a lot of headaches.

Do you think that instead of being subjected to detailed implementation (which you use the card inside), you could provide const_iteratorand findmethod for open class interface?

EDIT: . 5.2.10/7:

. 65) r " T1" " T2" ( T1 T2 T2 T1) , .

, const . , , , undefined.

+9

< int, const float * > const_cast , . , ( , , , ).

, Undefined , . , , , , .

+1

reinterpret_cast . ! const_iterators.

class A {
public:
  typedef std::map<int, float*> MapType;
  typedef MapType::const_iterator const_iterator;

  const_iterator begin () const { return m_Map.begin(); }

  const_iterator end () const { return m_Map.end(); }

private:
  std::map<int, float*> m_Map;
};


void some_function () {
  A my_map;

  // Code to build the map elided

  for (A::const_iterator iter = my_map.begin(); iter < my_map.end(); ++iter) {
    do_something_with_but_not_to (*iter);
  }

, , find, const_iterator.

0

, : , , ( , ), . ( TLS ++ 11) (, /), .

, ( ) , ( ). , , , , , , , . , , , segfault.

0

All Articles