A Discrete-Event Network Simulator
API
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
main-ptr.cc
Go to the documentation of this file.
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 PtrExample : public Object
9 {
10 public:
11  PtrExample ();
12  ~PtrExample ();
13  void Method (void);
14 };
16 {
17  std::cout << "PtrExample constructor" << std::endl;
18 }
20 {
21  std::cout << "PtrExample destructor" << std::endl;
22 }
23 void
25 {
26  std::cout << "PtrExample method" << std::endl;
27 }
28 
30 
31 static Ptr<PtrExample>
33 {
34  Ptr<PtrExample> prev = g_ptr;
35  g_ptr = p;
36  return prev;
37 }
38 
39 static void
40 ClearPtr (void)
41 {
42  g_ptr = 0;
43 }
44 
45 
46 
47 int main (int argc, char *argv[])
48 {
49  {
50  // Create a new object of type PtrExample, store it in global
51  // variable g_ptr
52  Ptr<PtrExample> p = CreateObject<PtrExample> ();
53  p->Method ();
54  Ptr<PtrExample> prev = StorePtr (p);
55  NS_ASSERT (prev == 0);
56  }
57 
58  {
59  // Create a new object of type PtrExample, store it in global
60  // variable g_ptr, get a hold on the previous PtrExample object.
61  Ptr<PtrExample> p = CreateObject<PtrExample> ();
62  Ptr<PtrExample> prev = StorePtr (p);
63  // call method on object
64  prev->Method ();
65  // Clear the currently-stored object
66  ClearPtr ();
67  // get the raw pointer and release it.
68  PtrExample *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
T * GetPointer(const Ptr< T > &p)
Definition: ptr.h:285
void Unref(void) const
Decrement the reference count.
void Method(void)
Definition: main-ptr.cc:24
static void ClearPtr(void)
Definition: main-ptr.cc:40
~PtrExample()
Definition: main-ptr.cc:19
int main(int argc, char *argv[])
Definition: main-ptr.cc:47
static Ptr< PtrExample > StorePtr(Ptr< PtrExample > p)
Definition: main-ptr.cc:32
a base class which provides memory management and object aggregation
Definition: object.h:63
PtrExample()
Definition: main-ptr.cc:15
static Ptr< PtrExample > g_ptr
Definition: main-ptr.cc:29