关于TBB/C++代码的问题

Jac*_*kie 4 c++ tbb

我正在阅读线程积木书。我不明白这段代码:

            FibTask& a=*new(allocate_child()) FibTask(n-1,&x);
FibTask& b=*new(allocate_child()) FibTask(n-2,&y);
Run Code Online (Sandbox Code Playgroud)

这些指令是什么意思?类对象引用和 new 一起工作吗?谢谢解释。

下面的代码是这个类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;

 }
};
Run Code Online (Sandbox Code Playgroud)

ken*_*ytm 5

new(pointer) Type(arguments);
Run Code Online (Sandbox Code Playgroud)

这种语法称为placement new,它假定该位置pointer已经分配,​​然后Type在该位置上简单地调用的构造函数,并返回一个Type*值。

然后将Type*其取消引用以给出Type&.

当您想要使用自定义分配算法时,会使用 Placement new,如您正在阅读的代码 ( allocate_child()) 中所示。