Why does std::pair expose member variables?

后端 未结 7 1553
孤独总比滥情好
孤独总比滥情好 2021-02-03 17:37

From http://www.cplusplus.com/reference/utility/pair/, we know that std::pair has two member variables, first and second.

Why did

相关标签:
7条回答
  • 2021-02-03 18:08

    The primary purpose of getters and setters is to gain control over access. That is to say, if you expose "first" as a variable, any class can read and write (if not const) it without telling the class it is a part of. In a number of cases, that can pose serious problems.

    For example, say you have a class that represents the number of passengers on a boat. You store the number of passengers as an integer. If you expose that number as a bare variable, it would be possible for external functions to write to it. That could leave you in a case where there are actually 10 passengers, but someone changed the variable (perhaps accidentally) to be 50. This is a case for a getter on the number of passengers (but not a setter, which would present the same problem).

    An example for getters and setters would be a class which represents a mathematical vector in which you want to cache certain information about the vector. Say you want to store the length. In this case, changing vec.x would probably change the length/magnitude. So, not only do you need to make x wrapped in a getter, you must provide a setter for x, which knows to update the vector's cached length. (Of course, most actual math libraries do not cache these values, and thus expose the variables.)

    So the question you ought to ask yourself in the context of using them is: is this class ever conceivably going to need to control or be alerted to changes to this variable?

    The answer in something like std::pair is a flat "no". There is no case for controlling access to members in a class whose sole purpose is to contain those members. There certainly is no need for pair to know if those variables have been touched, considering those are its only two members, and thus it has no state to update should either change. pair is ignorant of what it actually contains and its meaning, so tracking what it contains is not worth the effort.

    Depending on the compiler and how it is configured, getters and setters can introduce overhead. That's probably not important in most cases, but if you were to put them on something fundamental like std::pair, it would be a non-trivial concern. As such, their addition would need justified - which as I just explained, it cannot be.

    0 讨论(0)
提交回复
热议问题