Skip to Content
C++ Coding Standards: 101 Rules, Guidelines, and Best Practices
book

C++ Coding Standards: 101 Rules, Guidelines, and Best Practices

by Herb Sutter, Andrei Alexandrescu
October 2004
Intermediate to advanced
240 pages
6h 22m
English
Addison-Wesley Professional
Content preview from C++ Coding Standards: 101 Rules, Guidelines, and Best Practices

89. Write function objects correctly

Summary

Be cheap, be adaptable: Design function objects to be values that are cheap to copy. Where possible, make them adaptable by inheriting from unary_- or binary_function.

Discussion

Function objects are modeled on function pointers. Like function pointers, the convention is to pass them by value. All of the standard algorithms pass objects by value, and your algorithms should too. For example:

template<class InputIter, class Func>Function for_each( InputIter first, InputIter last, Function f );

Therefore, function objects must be cheap to copy and monomorphic (immune to slicing, so avoid virtual functions; see Item 54). But large and/or polymorphic objects are useful, and using them is okay; just hide ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ Core Guidelines Explained: Best Practices for Modern C++

C++ Core Guidelines Explained: Best Practices for Modern C++

Rainer Grimm
C++ Templates: The Complete Guide, 2nd Edition

C++ Templates: The Complete Guide, 2nd Edition

David Vandevoorde, Nicolai M. Josuttis, Douglas Gregor

Publisher Resources

ISBN: 0321113586Purchase book