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

后端 未结 4 810
南方客
南方客 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:47

    Locality and allowing the class to provide 'enough' features while maintaining encapsulation are some things to consider.

    If WebBrowser is reused in many places, the dependencies/clients may define multiple convenience functions. This keeps your classes (WebBrowser) lightweight and easy to manage.

    The inverse would be that the WebBrowser ends up pleasing all clients, and just becomes some monolithic beast that is difficult to change.

    Do you find the class is lacking functionality once it has been put to use in multiple scenarios? Do patterns emerge in your convenience functions? It's best (IMO) to defer formally extending the class's interface until patterns emerge and there is a good reason to add this functionality. A minimal class is easier to maintain, but you don't want redundant implementations all over the place because that pushes the maintenance burden onto your clients.

    If your convenience functions are complex to implement, or there is a common case which can improve performance significantly (e.g. to empty a thread safe collection with one lock, rather than one element at a time with a lock each time), then you may also want to consider that case.

    There will also be cases where you realize something is genuinely missing from the WebBrowser as you use it.

提交回复
热议问题