Why does std::pair expose member variables?

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

    It could be argued that std::pair would be better off having accessor functions to access its members! Notably for degenerated cases of std::pair there could be an advantage. For example, when at least one of the types is an empty, non-final class, the objects could be smaller (the empty base could be made a base which wouldn't need to get its own address).

    At the time std::pair was invented these special cases were not considered (and I'm not sure if the empty base optimization was allowed in the draft working paper at that time). From a semantic point there isn't much reason to have accessor functions, though: clearly, the accessors would need to return a mutable reference for non-const objects. As a result the accessor does not provide any form of encapsulation.

    On the other hand, it makes it [slightly] harder on the optimizer to see what's going on when accessor functions are used e.g. because additional sequence points are introduced. I could imagine that Meng Lee and Alexander Stepanov even measured whether there is a difference (nor did I). Even if they didn't, providing access to the members directly is certainly not slower than going through an accessor function while the reverse is not necessarily true.

    I wasn't part of the decision and the C++ standard doesn't have a rationale but I guess it was a deliberate decision to make the members public data members.

提交回复
热议问题