[Ns-developers] A question about downcast netdevice pointer.

Tom Henderson tomh at tomh.org
Thu Sep 25 10:04:10 PDT 2008


>-----Original Message-----
>From: Gustavo Carneiro [mailto:gjcarneiro at gmail.com]
>Sent: Thursday, September 25, 2008 08:16 AM
>To: ns-3-users at googlegroups.com
>Cc: 'ns-developers'
>Subject: Re: A question about downcast netdevice pointer.
>
>2008/9/25 Nan Li <kido.ln at gmail.com>
>
>>
>> Thanks your answer.
>> I just have a little confuse about this.
>>
>> dynamic_cast is a straight thought about converting base
>> class(netdevice) pointer to child class (csmanetdevice) pointer, which
>> means there is only one object.
>>
>> "aggregated" seems there are two objects aggregated together. Why
>> there is CsmaNetDevice object aggregated with a NetDevice object?
>>
>> I went throught the code, it seems there is only one object
>> (CsmaNetDevice) for each node.
>>
>> Am I right?
>
>
>You are right, there is only one object.
>
>I for one find using GetObject<SubClass>() for downcasts less intuitive than
>dynamic_cast, but I am aware some other developers don't quite agree with me
>for whatever reason.

Gustavo, yes, we discussed this before (in the context of Queue objects, IIRC).

The question was, whether GetObject<> () was the preferred approach for downcasting in ns-3, or whether dynamic_cast was preferred.

I think we agreed at the time that GetObject<> () was more suitable for finding out whether an object has an optional component aggregated to it (e.g., is there an EnergyModel that must be decremented when a wireless device makes a transmission?) but that pure downcasting was more straightforward to do dynamic_cast (although GetObject<> () does work in many cases), although the syntax could be improved as you suggest.  

>
>Although dynamic_cast<CsmaNetDevice*> (PeekPointer (dev)) is a bit more
>verbose.  Ideally I think it would make a lot of sense to have a
>smart-pointer based dynamic cast variant, something like:
>
>static inline Ptr<T2> DynamicCast<T2> (Ptr<T1> ptr)
>{
>   return Ptr<T2> (dynamic_cast<T2*> (PeekPointer (ptr)));
>}
>
>Unfortunately the idea got no traction, at the time.

In my reply, I was simply pointing out the other workable way but not prescribing it.  If this is considered ns-3 best practice (e.g., users SHOULD dynamic_cast but MAY GetObject), I will try to document it somewhere, and maybe we accept the above patch once tested?

Tom






More information about the Ns-developers mailing list