Class design vs. IDE: Are nonmember nonfriend functions really worth it?

后端 未结 7 1064
面向向阳花
面向向阳花 2020-12-21 00:01

In the (otherwise) excellent book C++ Coding Standards, Item 44, titled \"Prefer writing nonmember nonfriend functions\", Sutter and Alexandrescu recommend

7条回答
  •  半阙折子戏
    2020-12-21 00:58

    Scott Meyers has a similar opinion to Sutter, see here.

    He also clearly states the following:

    "Based on his work with various string-like classes, Jack Reeves has observed that some functions just don't "feel" right when made non-members, even if they could be non-friend non-members. The "best" interface for a class can be found only by balancing many competing concerns, of which the degree of encapsulation is but one."

    If a function would be something that "just makes sense" to be a member function, make it one. Likewise, if it isn't really part of the main interface, and "just makes sense" to be a non-member, do that.

    One note is that with overloaded versions of eg operator==(), the syntax stays the same. So in this case you have no reason not to make it a non-member non-friend floating function declared in the same place as the class, unless it really needs access to private members (in my experience it rarely will). And even then you can define operator!=() a non-member and in terms of operator==().

提交回复
热议问题