NS3中的三个核心类SimpleRefCount、Object和ObjectBase
首先明确下三个类的作用:
There are three special base classes used in ns-3. Classes that inherit from these base classes can instantiate objects with special properties. These base classes are:
- class
Object- class
ObjectBase- class
SimpleRefCountIt is not required that ns-3 objects inherit from these class, but those that do get special properties. Classes deriving from class Object get the following properties.
- the ns-3 type and attribute system (see Configuration and Attributes)
- an object aggregation system
- a smart-pointer reference counting system (class Ptr)
Classes that derive from class
ObjectBaseget the first two properties above, but do not get smart pointers. Classes that derive from classSimpleRefCount: get only the smart-pointer reference counting system.In practice, class
Objectis the variant of the three above that the ns-3 developer will most commonly encounter.
从官方文档中的这段叙述中,我们可以看出来,Object类的功能是类ObjectBase功能和SimpleRefCount的并集,后两者对前者的功能构成一个划分。
从代码中我们可以容易看出,Object类对SimpleRefCount有继承关系,而ObjectBase类独自实现,与前两者没有关系。
SimpleRefCount
NS3中由于SimpleRefCount类过于Simple,所以源文件和接口文件放在了同一个文件里。也就是文件simple-ref-count.h文件,在core目录下。
SimpleRefCount保有一个私有变量用来记录引用的数量,并通过两个函数Ref和Unref来对这个变量进行自增和自减操作,当判断为0时,执行内存的释放。
这两个函数不需要用户手动执行,而是通过智能指针Ptr来调用的。
ObjectBase
NS3中的ObjectBase类可以看作一个简化版的Object类,这个类主要的函数有:
SetAttribute
void SetAttribute (std::string name, const AttributeValue &value);
用来根据名称设置值,比如:
txQueue->SetAttribute ("MaxSize", StringValue ("60p"));
这条语句将名字MaxSize所绑定的变量的值设置为StringValue ("60p")。
TraceConnect
bool TraceConnect (std::string name, std::string context, const CallbackBase &cb);
这个函数用来在连接在tid中添加的对于类中某一变量的Trace,这个函数主要负责当Trace的值更好后通知回调函数cb。
Object
NS3中的object类继承了类SimpleRefCount<Object, ObjectBase, ObjectDeleter>。由于这个类继承了类ObjectBase,所以ObjectBase类中的成员函数类Object也有。除此之外,这个类中主要的函数有:
GetObject
template <typename T> inline Ptr<T> GetObject (void) const;
这个函数主要用来得到一个绑定的某类型的实例,比如:
Ptr<Ipv4> ipv4 = node->GetObject<Ipv4> ();
是把node中的Ipv4类型提取出来。
AggregateObject
/**
* Aggregate two Objects together.
*
* \param [in] other The other Object pointer
*
* This method aggregates the two Objects together: after this
* method returns, it becomes possible to call GetObject()
* on one to get the other, and vice-versa.
*
* This method calls the virtual method NotifyNewAggregates() to
* notify all aggregated Objects that they have been aggregated
* together.
*
* \sa NotifyNewAggregate()
*/
void AggregateObject (Ptr<Object> other);