Why does std::pair expose member variables?

后端 未结 7 1679
孤独总比滥情好
孤独总比滥情好 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:03

    Getters and setters are useful if one believes that abstraction is warranted to insulate users from design choices and changes in those choices, now or in the future.

    The typical example for "now" is that the setter/getter might have logic to validate and/or calculate the value - e.g., use a setter for a phone number, instead of directly exposing the field, so that you can check the format; use a getter for a collection so that the getter can provide a read-only view of the member's value (a collection) to the caller.

    The canonical (though bad) example for "changes in the future" is Point - should you expose x and y or getX() and getY()? The usual answer is to use getters/setters because at some time in the future you might want to change the internal representation from Cartesian to polar and you don't want your users to be impacted (or to have them depend on that design decision).

    In the case of std::pair - it is the intent that this class now and forever represent two and exactly two values (of arbitrary type) directly, and provide their values on demand. That's it. And that's why the design uses direct member access, rather than go through a getter/setter.

提交回复
热议问题