I have a class with an std::map of pointers as a member. Now, I’d like to expose that member in a read only fashion: modification is not allowed for neither the map, nor the objects pointed to. Internally I need those pointers to be non-const, and I want to expose them as const.
I do have a solution that compiles at least, but I’d like to know if there’s any hidden problems I’ll run into with this.
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’s a possible problem I can think of: if the internal layout of std::map is different for maps of pointers and maps of const pointers, then this will cause ugly bugs. But I cannot think of any sane reason why that would be the case. Anybody has any idea?
To clarify: I am aware that this is a hack, and there are safer solutions (like separate accessor functions). I am just wondering if this would break right away because of some piece of information I’m missing.
This is of course undefined (EDIT: it looks like it’s actually only unspecified) behavior because the two maps are (from the language point of view) totally unrelated types. It may appear to work now but sometime it’s going to break and cause a ton of headaches.
Did you consider that instead of exposing an implementation detail (that you’re using map internally) you could provide
const_iterators and afindmethod for your class’s public interface instead?EDIT:
See 5.2.10/7:
From that quote we conclude that casting from the map with non-const value type to the map with const value type has unspecified behavior. Further, actually dereferencing the converted pointer would probably violate the strict aliasing rules and result in undefined behavior.