1 // The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt 2 /* 3 This is an example illustrating the use of the dlib::std_allocator object. 4 5 In this example we will create the necessary typedefs to give the 6 dlib::std_allocator object to the standard string and vector objects 7 in the STL. Thus we will create versions of std::string and std::vector 8 that perform all their memory allocations and deallocations via one of 9 the dlib memory manager objects. 10 */ 11 12 13 // include everything we need for this example 14 #include <vector> 15 #include <iostream> 16 #include <string> 17 #include <dlib/std_allocator.h> 18 #include <dlib/memory_manager.h> 19 #include <dlib/memory_manager_stateless.h> 20 21 using namespace std; 22 using namespace dlib; 23 24 main()25int main() 26 { 27 // Make a typedef for an allocator that uses the thread safe memory_manager_stateless object with a 28 // global memory pool. This version of the memory_manager_stateless object keeps everything it allocates 29 // in a global memory pool and doesn't release any memory until the program terminates. 30 typedef std_allocator<char, memory_manager_stateless<char>::kernel_2_3a> alloc_char_with_global_memory_pool; 31 32 // Now make a typedef for a C++ standard string that uses our new allocator type 33 typedef std::basic_string<char, char_traits<char>, alloc_char_with_global_memory_pool > dstring; 34 35 36 // typedef another allocator for dstring objects 37 typedef std_allocator<dstring, memory_manager_stateless<char>::kernel_2_3a> alloc_dstring_with_global_memory_pool; 38 39 // Now make a typedef for a C++ standard vector that uses our new allocator type and also contains the new dstring 40 typedef std::vector<dstring, alloc_dstring_with_global_memory_pool > dvector; 41 42 // Now we can use the string and vector we have as we normally would. So for example, I can make a 43 // dvector and add 4 strings into it like so: 44 dvector v; 45 v.push_back("one"); 46 v.push_back("two"); 47 v.push_back("three"); 48 v.push_back("four"); 49 50 // And now we print out the contents of our vector 51 for (unsigned long i = 0; i < v.size(); ++i) 52 { 53 cout << v[i] << endl; 54 } 55 56 } 57 58