tags:

views:

103

answers:

2

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;

 }
};
+3  A: 
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()).

KennyTM
+2  A: 

The code

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

creates two sub-task of the this task and set this task as the successor of the created task. The space used to allocate these task is managed by the this task when thsi->allocate_child() is used as placement. The advantage is that these sub-task are owned by the this task and released when the current task is released automatically. Note that this can be done because the current task will out life its subtask as it depends on them.

This could also be written as

   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);

The use of references instead of pointers force people that will maintain this code to don't think that the pointers must be deleted, Well this is the explanation I have found.

Vicente Botet Escriba
I think using pointers and leaving an obvious (and copious) comment would have been better practice. It's not obvious that the destructors (as opposed to delete) don't need to be called.
anon
@Neil Yes you are right. The code is unusual and a little bit hard to read.
Vicente Botet Escriba