2

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?

Tony The Lion
  • 61,704
  • 67
  • 242
  • 415
user2020192
  • 109
  • 1
  • 6
  • 3
    Just copy it by value and be done with it. – Tony The Lion Feb 20 '13 at 08:11
  • "Which way would be better in performance?" Measure it in a realistic running scenario. But I would pass by value, and only think about it if it proves to be an issue. – juanchopanza Feb 20 '13 at 08:14
  • Tony's answer is almost certainly right. Shared pointer reference counting is way too heavy weight for this. You are better off copying and not worrying about it until you've profiled and demonstrated a performance issue. – Chris Hayden Feb 20 '13 at 08:14

1 Answers1

3

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.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455