c++ - Why provide two get functions -
class t {}; class accesst { public: boost::shared_ptr<const t> gett() const {return m_t;} boost::shared_ptr<t> gett() {return m_t;} private: boost::shared_ptr<t> m_t; };
question> saw lots of similar codes above in legacy project. don't understand point of doing so. why not provide next instead:
class t {}; class accesstmodified { public: boost::shared_ptr<t> gett() const { homecoming m_t; } private: boost::shared_ptr<t> m_t; };
the initial argument may boost::shared_ptr<const t> gett() const
not allow const object modifies t accident. if case, practice such functions should provide 2 versions? me, sense tedious!
you correct: purpose of boost::shared_ptr<const t> gett() const
ensure const
objects can't modify t accident.
in c++, known const correctness , considered c++ design. said, results in getters having 2 versions (a const
, non-const
version). can tedious (although it's not bad 1 time used it), results can quite useful. const correctness lets declare functions like
void dosomething(const accesst& item);
that promise not modify item
compiler throws error if dosomething
that's declared perchance modifying item
.
although const correctness considered c++ design, developers decide overhead of having declare const , non-const versions of functions more problem it's worth.
the c++ faq has a whole section on const correctness, if you're interested in more information.
c++ boost
No comments:
Post a Comment