c++ - deep_const_ptr copy constructor -
template <class t> class deep_const_ptr { t * priv; public: deep_const_ptr(const deep_const_ptr & p_other); // copy ctor t const * operator->() const; t * operator->(); ..... // other crap }; void cheese::dothings(const deep_const_ptr<cheese> p_other) { deep_const_ptr<cheese> awaygoestheconst(p_other); // don't want work. awaygoestheconst->doterriblethings(); }
i'd block copy construction const non-const.
maybe doesn't make sense?
might possible new c++11 / 14 / 17?
edit:
yes, issue if don't give copy constructor, stl containers wont work. , i'd quite need them work.
edit:
deep_const_ptr solution came when faced problem of stl containers , const objects.
class shape { private: std::list<vertex *> m_vertices; public: virtual void std::list<vertex*> * const getvertices() { return &m_vertices; } virtual void std::list<vertex const *> * const getvertices() const { return &m_vertices; } // doesn't work, cannot convert between different types of lists }
i want provide immutable vertex objects immutable shape.
the 2 solutions came custom deep_const_ptr pointer types , custom lists where
vertex const *& operator[](unsigned int) const;
i assume after deep-const-pointer implementation , copying. found out, simple copy constructor not do, since lose const on pointer. there no other way disallow const removal on outer object, need disable copy constructor. current version of question not make clear why problem. comments , previous question, can infer want use pointer in containers, std::vector<> specifically. key making work disable copy, enable move (note need rvalue-reference support this, part of c++11):
template <class t> class deep_const_ptr { t * priv; public: deep_const_ptr(const deep_const_ptr &) = delete; // not allow this! deep_const_ptr& operator=(const deep_const_ptr &) = delete; // nor this! deep_const_ptr(deep_const_ptr &&) = default; // okay deep_const_ptr& operator=(deep_const_ptr &&) = default; // this! t const * operator->() const; t * operator->(); ..... // other crap };
containers typically need move, not copy, work.
if need support copy, need different type supports const access. example, specialize deep_const_ptr
const t
, implement const variant of operator->
, operator*
in there. additionally, you'd allow "demotion" of deep_const_ptr deep_const_ptr via conversion operator. implies sort of multiple owner handling, such reference counting, i'm going leave out. it's weird const , non-const version behave differently, it's decision. personally, i'd recommend sticking move.
Comments
Post a Comment