why function objects should be pass-by-value

前端 未结 3 1939
粉色の甜心
粉色の甜心 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:41

    The #1 reason to pass function objects by value is because the standard library requires that function objects you pass to its algorithms be copyable. C++11 §25.1/10:

    [ Note: Unless otherwise specified, algorithms that take function objects as arguments are permitted to copy those function objects freely. Programmers for whom object identity is important should consider using a wrapper class that points to a noncopied implementation object such as reference_wrapper (20.8.3), or some equivalent solution. —end note ]

    The other answers do a great job of explaining the rationale.

提交回复
热议问题