c++ - How to expose a map of pointers as a map of const pointers? -
i have class std::map of pointers member. now, i'd expose member in read fashion: modification not allowed neither map, nor objects pointed to. internally need pointers non-const, , want expose them const.
i have solution compiles @ least, i'd know if there's hidden problems i'll run this.
class { 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 possible problem can think of: if internal layout of std::map different maps of pointers , maps of const pointers, cause ugly bugs. cannot think of sane reason why case. has idea?
to clarify: aware hack, , there safer solutions (like separate accessor functions). wondering if break right away because of piece of information i'm missing.
this of course undefined (edit: looks it's unspecified) behavior because 2 maps (from language point of view) totally unrelated types. may appear work sometime it's going break , cause ton of headaches.
did consider instead of exposing implementation detail (that you're using map internally) provide const_iterator
s , find
method class's public interface instead?
edit: see 5.2.10/7:
a pointer object can explicitly converted pointer object of different type. 65) except converting rvalue of type “pointer t1” type “pointer t2” (where t1 , t2 object types , alignment requirements of t2 no stricter of t1) , original type yields original pointer value, result of such pointer conversion unspecified.
from quote conclude casting map non-const value type map const value type has unspecified behavior. further, dereferencing converted pointer violate strict aliasing rules , result in undefined behavior.
Comments
Post a Comment