关于 TBB/C++ 的问题代码
我正在阅读《线程构建块》一书。我不明白这段代码:
FibTask& a=*new(allocate_child()) FibTask(n-1,&x);
FibTask& b=*new(allocate_child()) FibTask(n-2,&y);
这些指令是什么意思?类对象引用和 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;
}
};
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;
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此语法称为 placement new,假设位置
指针
已经分配,然后简单地在该位置调用Type
的构造函数,并返回一个Type*
价值。然后这个
Type*
被取消引用以给出Type&
。当您想要使用自定义分配算法时,请使用 Placement new,如您正在阅读的代码 (
allocate_child()
) 所示。This syntax is called placement new, which assumes the location
pointer
is already allocated, then the constructor ofType
is simply called on that location, and return aType*
value.Then this
Type*
is dereferenced to give aType&
.Placement new is used when you want to use a custom allocation algorithm, as demonstrated in the code you're reading (
allocate_child()
).该代码
创建了该任务的两个子任务,并将该任务设置为所创建任务的后继任务。当 thsi->allocate_child() 用作放置时,用于分配这些任务的空间由该任务管理。优点是这些子任务归本任务所有,并在当前任务释放时自动释放。请注意,这是可以完成的,因为当前任务将超过其子任务的寿命,因为它依赖于它们。
这也可以写为
使用引用而不是指针迫使维护此代码的人不认为必须删除指针,这就是我找到的解释。
The code
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
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.