0

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.

W.F.
  • 13,888
  • 2
  • 34
  • 81
spectre
  • 113
  • 1
  • 9

1 Answers1

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.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • Thank you. I am not aware of both smart pointers and template functions. So how can i understand this then? – spectre Nov 08 '16 at 11:38
  • Hi, i have gone through some basics of template. But didn't come across anything similar to the one that you have mentioned in the answer. Can you please give me a reference ( preferably video link) for that? – spectre Nov 10 '16 at 13:02