0

I am trying to create a copy of a boost::function by using a pointer and call that function using that pointer. My questions are

  1. cloning a boost::function that way is something correct
  2. the call to fp->target() should call or not the function wrapped by the boost::function?

Thanks a lot

  boost::function<void()> f = boost::bind(&my_f,my_value);
  boost::function<void()> fp* = new boost::function<void()>( f ); // clone f

  typedef void(*fptr_type)();
  fp->target<fptr_type>();  // doesn't work! Is this correct?

  fp->operator(); // doesn't compile
                  //=>error: statement cannot resolve address of overloaded function
Abruzzo Forte e Gentile
  • 14,423
  • 28
  • 99
  • 173
  • 2
    Why, oh *why* are you `new`ing the copy?! Please, tell me *one* sensible reason. – Xeo Mar 09 '12 at 11:31

2 Answers2

2

If boost::function provides a copy constructor, you can assume that it will work and take care of all the lifetime issues of f in this case ( otherwise it wouldn't be provided, and you should file a bug report on their bugzilla ).

fp->operator();

Is just the function, what you're meaning to do is:

fp->operator()();

Or as above poster:

(*fp)();
Ylisar
  • 4,293
  • 21
  • 27
1

Look this code, I think that is what you want to do :

void my_f(void)
{
    cout << "hello";
}

int main(void){

  boost::function<void()> f = boost::bind(&my_f);
  boost::function<void()>* fp = new boost::function<void()>( f ); 

  typedef void(*fptr_type)();
  fp->target<fptr_type>(); 

  (*fp)();
}

Compiled with GCC, and that works well, I can see the cout.

Adrien BARRAL
  • 3,474
  • 1
  • 25
  • 37