Ptr< Node> a = CreateObject<节点> ();
当我在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();
或在 const 前缀$ c> xxx 。
or they prefix const
before xxx
.
我想这是用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.