When should I prefer non-member non-friend functions to member functions?

后端 未结 4 813
南方客
南方客 2020-12-08 03:27

Meyers mentioned in his book Effective C++ that in certain scenarios non-member non-friend functions are better encapsulated than member functions.

Example:

4条回答
  •  不思量自难忘°
    2020-12-08 03:41

    Non-member functions are commonly used when the developer of a library wants to write binary operators that can be overloaded on either argument with a class type, since if you make them a member of the class you can only overload on the second argument (the first is implicitly an object of that class). The various arithmetic operators for complex are perhaps the definitive example for this.

    In the example you cite, the motivation is of another kind: use the least coupled design that still allows you to do the job.

    This means that while clearEverything could (and, to be frank, would be quite likely to) be made a member, we don't make it one because it does not technically have to be. This buys you two things:

    1. You don't have to accept the responsibility of having a clearEverything method in your public interface (once you ship with one, you 're married to it for life).
    2. The number of functions with access to the private members of the class is one lower, hence any changes in the future will be easier to perform and less likely to cause bugs.

    That said, in this particular example I feel that the concept is being taken too far, and for such an "innocent" function I 'd gravitate towards making it a member. But the concept is sound, and in "real world" scenarios where things are not so simple it would make much more sense.

提交回复
热议问题