Ptr a = CreateObject < Node> ();

2019-09-14 05:51发布

问题:

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 > ();  

In some other cases they use similar syntax, but RHS is quite different.

HelperClass help;

Ptr< xxx > a = help.somethingrandom();

or they prefix const before xxx.

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.

回答1:

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.

The standard library has an equivalent std::shared_ptr/std::unique_ptr with matching std::make_shared/std::make_unique functions.



标签: c++ class object