Std :: function vs std :: function & as function argument

consider the three functions below,

func1(std::function<size_t(...) > f, ...);
func2(std::function<size_t(...) >& f );
func3(const std::function<size_t(...)> &f);  

      

For any other argument argument passed by value / copy-constructor, pass by reference and pass by constant reference have a clear context and their use cases are well known.

In the case of objects function<>

, for example, traversing a constant reference is the save time (like calling a potential copy constructor) or space (no need to pass the whole function object onto the stack)? How big is the function-function, in the first place, to make sure it passed a const reference? I'm guessing this will roughly be the size of the pointer - is that correct?

+3


source to share


2 answers


In the case of objects function<>

, for example, traversing a constant reference is the save time (like calling a potential copy constructor) or space (no need to pass the whole function object onto the stack)?

May be. You must measure it.

How big is a function-function in the first place to make it pass by reference const?



It depends on the implementation. You must measure it.

I assume it will be about this pointer size - is this correct?

It is recommended that implementations use "small object optimization" so that the small function object is stored within the object function

rather than dynamically allocated. In this case, it will be the size (or slightly larger) of this object. Otherwise, it would be the size (or slightly larger) of the pointer to the dynamic object.

+2


source


Take gcc 4.9 and check:

cout << sizeof(int(*)(double, double)) << endl;
cout << sizeof(function<int(double, double)>) << endl; 

      

outputs:



8
32

      

The size of the callee is of course larger than the size of the pointer, and you might find it helpful to pass it by const reference. It's a good idea, however, only if you can guarantee that the object (whether it starts std::function<>

or not) you are passing a reference constant while you are about to use it.

+2


source







All Articles