Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A question about TBB/C++ code

Tags:

c++

tbb

I am reading The thread building block book. I do not understand this piece of code:

            FibTask& a=*new(allocate_child()) FibTask(n-1,&x);
FibTask& b=*new(allocate_child()) FibTask(n-2,&y);

What do these directive mean? class object reference and new work together? Thanks for explanation.

The following code is the defination of this class FibTask.

class FibTask: public task

{
public:

 const long n;
    long* const sum;
 FibTask(long n_,long* sum_):n(n_),sum(sum_)
 {}
 task* execute()
 {
  if(n<CutOff)
  {
   *sum=SFib(n);
  }
  else
  {
   long x,y;

   FibTask& a=*new(allocate_child()) FibTask(n-1,&x);
   FibTask& b=*new(allocate_child()) FibTask(n-2,&y);
   set_ref_count(3);
   spawn(b);
   spawn_and_wait_for_all(a);
   *sum=x+y;
  }
  return 0;

 }
};
like image 599
Jackie Avatar asked Jan 22 '23 03:01

Jackie


1 Answers

new(pointer) Type(arguments);

This syntax is called placement new, which assumes the location pointer is already allocated, then the constructor of Type is simply called on that location, and return a Type* value.

Then this Type* is dereferenced to give a Type&.

Placement new is used when you want to use a custom allocation algorithm, as demonstrated in the code you're reading (allocate_child()).

like image 173
kennytm Avatar answered Feb 01 '23 07:02

kennytm