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;
}
};
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()
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With