Question

I'm attempting to use std::function as a callback handler.

Such like this,

void some_job( int arg1, std::function<void(int)> & callback )
{       
   callback( process(arg1) );
}

In this example i used pass-by-reference.

But the problem is, I can't guarantee the std::function object callback is still exists because the function executed in asynchronized context in my program.

So I have to manage life cycle of the function object, and I thought two way for it.

  1. using pass-by-value(copy)

  2. using std::shared_ptr

I know the size of std::function is fixed in 24 byte in my system and std::shared_ptr is 8.

But copying std::shared_ptr cause additional overhead managing it's reference counter. (Furthermore I can't find any smart and neat way to make a shared_ptr object of std::function.)

Which way would be better in performance?

Was it helpful?

Solution

If you are in so time-critical a part of your program that it worries you whether it's faster to copy 24 bytes or 8 bytes + sharing overhead, you will have to implement both and use a profiler to find out which is better in your particular scenario. And in such case, you should also consider an entirely different approach which would bypass the virtual call probably hidden inside std::function::operator().

Otherwise, I'd just take the parameter by value and let the optimiser do its job.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top