HOWTO resolve circular references in ns-3 memory disposal: Difference between revisions
Jump to navigation
Jump to search
| Line 41: | Line 41: | ||
Now the following code: | Now the following code: | ||
<pre> | |||
int main(int argc, char* argv[]) | int main(int argc, char* argv[]) | ||
{ | { | ||
| Line 50: | Line 50: | ||
b->Dispose(); //a->Dispose() will work as well | b->Dispose(); //a->Dispose() will work as well | ||
} | } | ||
</pre> | |||
will not longer have a memory leak. | will not longer have a memory leak. | ||
Revision as of 17:54, 30 August 2013
HOWTO resolve smart pointer circular references in ns-3 memory disposal
class A : public Object
{
public:
static TypeId GetTypeId (void);
Callback<void> m_callback;
};
class B : public Object
{
public:
static TypeId GetTypeId (void);
void CallbackMethodB (void);
};
int main(int argc, char* argv[])
{
Ptr<A> a = CreateObject<A>();
Ptr<B> b = CreateObject<B>();
a->m_callback = MakeCallback (&B::CallbackMethodB, b);
b->AggregateObject(a);
}
==15749== LEAK SUMMARY:
==15749== definitely lost: 40 bytes in 1 blocks
==15749== indirectly lost: 152 bytes in 5 blocks
==15749== possibly lost: 0 bytes in 0 blocks
The preferred way to break reference cycles like this in ns-3 is to use Object::Dispose(). This method will call the DoDispose method on the object that it is called on as well as all other objects aggregated on to it. In the above example Class A is aggregated to Class B so we make the following change to Class A:
class A : public Object
{
public:
static TypeId GetTypeId (void);
Callback<void> m_callback;
virtual void DoDispose (void)
{
m_callback = MakeNullCallback<void>();
}
};
Now the following code:
int main(int argc, char* argv[])
{
Ptr<A> a = CreateObject<A>();
Ptr<B> b = CreateObject<B>();
a->m_callback = MakeCallback (&B::CallbackMethodB, b);
b->AggregateObject(a);
b->Dispose(); //a->Dispose() will work as well
}
will not longer have a memory leak.
==16877== LEAK SUMMARY:
==16877== definitely lost: 0 bytes in 0 blocks
==16877== indirectly lost: 0 bytes in 0 blocks
==16877== possibly lost: 0 bytes in 0 blocks