Ptr< Node> a = CreateObject<节点> (); [英] Ptr<Node> a = CreateObject < Node > ();

查看:103
本文介绍了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();

或在<$ c之前加上 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.

这篇关于Ptr&lt; Node&gt; a = CreateObject&lt;节点&gt; ();的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆