why function objects should be pass-by-value

前端 未结 3 1923
粉色の甜心
粉色の甜心 2020-12-08 15:44

I have just read the classic book \"Effective C++, 3rd Edition\", and in item 20 the author concludes that built-in types, STL iterators and function object types ar

3条回答
  •  时光说笑
    2020-12-08 16:27

    From Effective STL (since you seems to like Scott Meyers) item 38 Design functor classes for pass-by-value.

    "In both C and C++ function pointers are passed by value. STL Function objects are modeled after function pointers, so the convention in the STL is that function objects, too, are passed by value when passed to and from functions."

    This has some benefits and some implications, like @Jerry Coffin said, the compiler can make some optimizations like inlining the code to avoid function calls (You have to mark your functor as inline). A good example of this case is the qsort vs std::sort performance comparison, where std::sort using inline functors outperform qsort by a lot, you can find more information on this on Effective STL where it is discussed extensively and mentioned in several chapters.

    This also has several implications too, since function objects are passed and returned by value, you have to make sure your object have a well defined copy mechanisms, are small in size (otherwise it could get expensive), and are monomorphic (since passing polymorphic objects by value may result in object slicing).

提交回复
热议问题