4

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 type of argument passing by value/copy-constructor, passing by reference and passing by const reference have a clear context and their use cases are well known.

For the case of function<> objects, would e.g. passing by const reference save time (from e.g. calling potential copy constructor) or space (no need to pass a whole function object to the stack)? How big is a function object in the first place to make it worth passing passing by const reference? my guess would be that it would roughly be the size of a pointer - is this correct?

k_l
  • 189
  • 1
  • 3
  • I've always gotten the impression that `std::function` is actually pretty heavy-weight. It has to be able to contain a class instance for member function pointers, for example. And it could potentially be wrapping a bind expression or lambda with captured variables, which obviously need to store extra state that would need to be copied (unless it was heap allocated, I suppose). – Cameron Apr 29 '15 at 16:40
  • No: A function object (eg. holding a lambda) might be quite expensive to copy. –  Apr 29 '15 at 16:41
  • @Cameron: It depends on what type of function object it wraps, and how it's implemented. If it wraps a small (or even empty) object, and is optimised not to dynamically allocate it, then it can be very lightweight. – Mike Seymour Apr 29 '15 at 16:43

2 Answers2

2

Let's take gcc 4.9 and check:

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

outputs:

8
32

Size of the callable is, of course, bigger than the pointer size, and you might benefit from passing it by const reference. That is a good idea, however, only if you can guarantee that the object (regardless of it begin an std::function<> or not) you pass by const reference lives as long as you're intending to use it.

Adam Kosiorek
  • 1,438
  • 1
  • 13
  • 17
1

For the case of function<> objects, would e.g. passing by const reference save time (from e.g. calling potential copy constructor) or space (no need to pass a whole function object to the stack)?

Maybe. You'd have to measure it.

How big is a function object in the first place to make it worth passing passing by const reference?

It depends on the implementation. You'd have to measure it.

my guess would be that it would roughly be the size of a pointer - is this correct?

Implementations are encouraged to use a "small object optimisation", so that a small function object is stored inside the function object, rather than dynamically allocated. In that case it will be the size of (or slightly larger than) that object. Otherwise, it would be the size of (or slightly larger than) a pointer to the dynamic object.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644