Prevent unnecessary copies of C++ functor objects

后端 未结 5 1144
野的像风
野的像风 2020-12-09 10:39

I have a class which accumulates information about a set of objects, and can act as either a functor or an output iterator. This allows me to do things like:



        
5条回答
  •  悲&欢浪女
    2020-12-09 10:58

    You have stumbled upon an often complained about behavior with . There are no restrictions on what they can do with the functor, so the answer to your question is no: there is no way to encourage the compiler to elide the copies. It's not (always) the compiler, it's the library implementation. They just like to pass around functors by value (think of std::sort doing a qsort, passing in the functor by value to recursive calls, etc).

    You have also stumbled upon the exact solution everyone uses: have a functor keep a reference to the state, so all copies refer to the same state when this is desired.

    I found this ironic:

    But this makes it impossible to use the "functional" style of immutable objects, and just generally isn't as nice.

    ...since this whole question is predicated on you having a complicated stateful functor, where creating copies is problematic. If you were using "functional" style immutable objects this would be a non-issue - the extra copies wouldn't be a problem, would they?

提交回复
热议问题