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;
};

Questions> In the previous project, I saw many similar codes, as indicated above. I really don't understand how to do this. Why not just simply indicate instead:

class T
{};

class AccessTModified
{
public:
    boost::shared_ptr<T> getT() const { return m_T; }

private:
    boost::shared_ptr<T> m_T;
};

The initial argument may be that it boost::shared_ptr<const T> getT() constdoes not allow the const object to modify T randomly. If so, is it a practice that all such functions should provide two versions? This is very tiring for me!

+5
source share
2 answers

You are right: the goal boost::shared_ptr<const T> getT() constis to ensure that objects constcannot modify T by accident.

++ const correctness ++-. , , (a const const). ( , ), . ,

void DoSomething(const AccessT& item);

item, , DoSomething , item.

const ++, , , , .

++ const, .

+9

, accessor, AccessT AccessTconst . , , - .

- , , "const pointer" "pointer to const". AccessT setT, .

const_, , . , const_iterator iterator .

+1

All Articles