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.
source
share