Ptr& lt; Node& gt;a = CreateObject& lt;节点& gt;(); [英] Ptr<Node> a = CreateObject < Node > ();
问题描述
当我在NS-3(网络模拟器)中浏览不同的示例时,我遇到了这样的定义.我不知道这个语法到底是什么意思.
While i am going through different examples in NS-3 ( network simulator) i came across a definition like this. I coudn't figure out what exactly this syntax means.
Ptr<Node> a = CreateObject < Node > ();
在其他一些情况下,它们使用相似的语法,但RHS却大不相同.
In some other cases they use similar syntax, but RHS is quite different.
HelperClass帮助;
HelperClass help;
Ptr< xxx > a = help.somethingrandom();
,或者在 xxx
之前加 const
前缀.
我想这是用c ++创建对象的另一种方式.但这仍然令人困惑.任何人都可以详细说明发生了什么吗?提前致谢.
I guess this is a different way of creating objects in c++. But it is still confusing. Can anyone please elaborate whats happening ? Thanks in advance.
推荐答案
假定 Ptr
是一些智能指针类.看来 CreateObject
是模板函数,其实现可以简单地归结为:
Assuming Ptr
is some smart pointer class. It seems CreateObject
is template function, with implementation that simply boils down to this:
template<typename Obj>
Ptr<Obj> CreateObject() {
return Ptr<Obj>(new Obj);
}
这个想法是代码是通用的,它将适用于任何类型.如果构造函数碰巧抛出异常,则使用函数可确保在多次初始化期间不会发生资源泄漏.
The idea is that the code is generic, it will work for any type. Using a function ensures no resources leak during multiple initializations, if a constructor happens to throw an exception.
标准库具有等效的 std :: shared_ptr
/ std :: unique_ptr
和匹配的 std :: make_shared
/ std:: make_unique
函数.
The standard library has an equivalent std::shared_ptr
/std::unique_ptr
with matching std::make_shared
/std::make_unique
functions.
这篇关于Ptr& lt; Node& gt;a = CreateObject& lt;节点& gt;();的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!