A Discrete-Event Network Simulator
API
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Groups Pages
main-ptr.cc
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 #include "ns3/ptr.h"
3 #include "ns3/object.h"
4 #include <iostream>
5 
6 using namespace ns3;
7 
8 class A : public Object
9 {
10 public:
11  A ();
12  ~A ();
13  void Method (void);
14 };
15 A::A ()
16 {
17  std::cout << "A constructor" << std::endl;
18 }
19 A::~A()
20 {
21  std::cout << "A destructor" << std::endl;
22 }
23 void
24 A::Method (void)
25 {
26  std::cout << "A method" << std::endl;
27 }
28 
29 static Ptr<A> g_a = 0;
30 
31 static Ptr<A>
32 StoreA (Ptr<A> a)
33 {
34  Ptr<A> prev = g_a;
35  g_a = a;
36  return prev;
37 }
38 
39 static void
40 ClearA (void)
41 {
42  g_a = 0;
43 }
44 
45 
46 
47 int main (int argc, char *argv[])
48 {
49  {
50  // Create a new object of type A, store it in global
51  // variable g_a
52  Ptr<A> a = CreateObject<A> ();
53  a->Method ();
54  Ptr<A> prev = StoreA (a);
55  NS_ASSERT (prev == 0);
56  }
57 
58  {
59  // Create a new object of type A, store it in global
60  // variable g_a, get a hold on the previous A object.
61  Ptr<A> a = CreateObject<A> ();
62  Ptr<A> prev = StoreA (a);
63  // call method on object
64  prev->Method ();
65  // Clear the currently-stored object
66  ClearA ();
67  // get the raw pointer and release it.
68  A *raw = GetPointer (prev);
69  prev = 0;
70  raw->Method ();
71  raw->Unref ();
72  }
73 
74 
75  return 0;
76 }
smart pointer class similar to boost::intrusive_ptr
Definition: ptr.h:59
#define NS_ASSERT(condition)
Definition: assert.h:64
void Unref(void) const
a base class which provides memory management and object aggregation
Definition: object.h:63