Merge pull request #2216 from jwillemsen/jwi-cxxversionchecks
[ACE_TAO.git] / ACE / examples / APG / Containers / Allocator.cpp
blob0cb42e3d45d0d55622438d830aad347c2e1a0aad
1 #include "ace/Containers.h"
2 #include "ace/Malloc_T.h"
3 #include "ace/Synch.h" // Needed for the lock.
4 #include "DataElement.h"
6 class StackExample
8 public:
9 // Illustrate all the differnet
10 // types of stacks provided by ACE.
11 int run ();
13 private:
14 // Illustrate the use of an unbounded stack.
15 int runUnboundedStack (ACE_Allocator* allocator);
18 // Listing 1 code/ch05
19 int StackExample::run ()
21 ACE_TRACE ("StackExample::run");
23 ACE_Allocator *allocator = 0;
24 size_t block_size = sizeof(ACE_Node<DataElement>);
25 ACE_NEW_RETURN
26 (allocator,
27 ACE_Dynamic_Cached_Allocator<ACE_Null_Mutex>
28 (100 + 1, block_size),
29 -1);
31 ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n# of live objects %d\n"),
32 DataElement::numOfActiveObjects ()));
34 ACE_TEST_ASSERT (this->runUnboundedStack (allocator) != -1);
36 ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n# of live objects %d\n"),
37 DataElement::numOfActiveObjects ()));
39 delete allocator;
40 return 0;
42 // Listing 1
43 // Listing 2 code/ch05
44 int StackExample::runUnboundedStack (ACE_Allocator* allocator)
46 ACE_TRACE ("StackExample::runUnboundedStack");
48 // Pass in an allocator during construction.
49 ACE_Unbounded_Stack<DataElement> ustack (allocator);
51 for (int m = 0; m < 100; m++)
53 DataElement elem (m);
54 int result = ustack.push (elem);
55 if (result == -1)
56 ACE_ERROR_RETURN
57 ((LM_ERROR, ACE_TEXT ("%p\n"),
58 ACE_TEXT ("Push Next Element")),
59 -1);
62 void* furtherMemory = 0;
63 furtherMemory = allocator->malloc
64 (sizeof(ACE_Node<DataElement>));
65 ACE_TEST_ASSERT (furtherMemory == 0);
67 // No memory left..
68 ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("%p\n"),
69 ACE_TEXT ("No memory..")));
71 // Free up some memory in the allocator.
72 DataElement e;
73 for (int n = 0; n < 10; n++)
75 ustack.pop (e);
78 furtherMemory =
79 allocator->malloc (sizeof (ACE_Node<DataElement>));
80 ACE_TEST_ASSERT (furtherMemory != 0);
82 return 0;
84 // Listing 2
86 int ACE_TMAIN (int, ACE_TCHAR *[])
88 StackExample se;
89 return se.run ();