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> I saw lots of similar codes as above in the legacy project.
I really don’t understand the point of doing so.
Why not just simply provide the following 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 boost::shared_ptr<const T> getT() const will not let const object modifies the T by accident. If that is the case, is it a practice that all such functions should provide two versions? To me, I feel very tedious!
You are correct: the purpose of
boost::shared_ptr<const T> getT() constis to ensure thatconstobjects can’t modify the T by accident.In C++, this is known as const correctness and is usually considered to be good C++ design. As you said, it often results in getters having two versions (a
constand a non-constversion). It can be initially tedious (although it’s not bad once you get used to it), but the results can be quite useful. Const correctness lets you declare functions likethat promise not to modify
itemso that the compiler throws an error ifDoSomethingdoes anything that’s declared as possibly modifyingitem.Although const correctness is usually considered to be good C++ design, some developers decide that the overhead of having to declare const and non-const versions of some functions to be more trouble than it’s worth.
The C++ FAQ has a whole section on const correctness, if you’re interested in more information.