1 //////////////////////////////////////////////////////////////////////////////
2 //
3 // (C) Copyright Ion Gaztanaga 2004-2012. Distributed under the Boost
4 // Software License, Version 1.0. (See accompanying file
5 // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6 //
7 // See http://www.boost.org/libs/interprocess for documentation.
8 //
9 //////////////////////////////////////////////////////////////////////////////
10
11 #include <boost/interprocess/allocators/allocator.hpp>
12 #include <boost/interprocess/managed_shared_memory.hpp>
13 #include <boost/interprocess/containers/vector.hpp>
14 #include <boost/interprocess/containers/list.hpp>
15 #include <iostream>
16 #include <functional>
17 #include "print_container.hpp"
18 #include <string>
19 #include "get_process_id_name.hpp"
20
21 struct InstanceCounter
22 {
InstanceCounterInstanceCounter23 InstanceCounter(){++counter;}
InstanceCounterInstanceCounter24 InstanceCounter(const InstanceCounter&){++counter;}
~InstanceCounterInstanceCounter25 ~InstanceCounter(){--counter;}
26 static std::size_t counter;
27 };
28
29 std::size_t InstanceCounter::counter = 0;
30
31 using namespace boost::interprocess;
32
33
main()34 int main ()
35 {
36 const int memsize = 16384;
37 const char *const shMemName = test::get_process_id_name();
38
39 try{
40 shared_memory_object::remove(shMemName);
41
42 //Named allocate capable shared mem allocator
43 managed_shared_memory segment(create_only, shMemName, memsize);
44
45 //STL compatible allocator object, uses allocate(), deallocate() functions
46 typedef allocator<InstanceCounter,
47 managed_shared_memory::segment_manager>
48 inst_allocator_t;
49 const inst_allocator_t myallocator (segment.get_segment_manager());
50
51 typedef vector<InstanceCounter, inst_allocator_t> MyVect;
52
53 //We'll provoke an exception, let's see if exception handling works
54 try{
55 //Fill vector until there is no more memory
56 MyVect myvec(myallocator);
57 int i;
58 for(i = 0; true; ++i){
59 myvec.push_back(InstanceCounter());
60 }
61 }
62 catch(boost::interprocess::bad_alloc &){
63 if(InstanceCounter::counter != 0)
64 return 1;
65 }
66
67 //We'll provoke an exception, let's see if exception handling works
68 try{
69 //Fill vector at the beginning until there is no more memory
70 MyVect myvec(myallocator);
71 int i;
72 InstanceCounter ic;
73 for(i = 0; true; ++i){
74 myvec.insert(myvec.begin(), i, ic);
75 }
76 }
77 catch(boost::interprocess::bad_alloc &){
78 if(InstanceCounter::counter != 0)
79 return 1;
80 }
81 catch(std::length_error &){
82 if(InstanceCounter::counter != 0)
83 return 1;
84 }
85 }
86 catch(...){
87 shared_memory_object::remove(shMemName);
88 throw;
89 }
90 shared_memory_object::remove(shMemName);
91 return 0;
92 }
93
94