Advertisement
tyler569

Custom allocator working on libc++ only

Aug 17th, 2018
394
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 KB | None | 0 0
  1.  
  2. #include <cstdlib>
  3. #include <cstdio>
  4. #include <memory>
  5. #include <vector>
  6.  
  7. using std::vector;
  8. using std::size_t;
  9.  
  10. template <typename T>
  11. struct mallocator : std::allocator<T> {
  12.     using value_type = T;
  13.  
  14.     T *allocate(size_t cnt) {
  15.         std::printf("custom allocate called!\n");
  16.         return static_cast<T *>(std::malloc(cnt * sizeof(T)));
  17.     }
  18.     void deallocate(T *mem) {
  19.         return std::free(mem);
  20.     }
  21.     void deallocate(T *mem, size_t) {
  22.         return std::free(mem);
  23.     }
  24. };
  25.  
  26. int main() {
  27.     vector<int, mallocator<int>> foo = {1, 2, 3, 4, 5};
  28.  
  29.     for (int i=0; i<10; i++) {
  30.         foo.push_back(8);
  31.     }
  32. }
  33.  
  34.  
  35. ///////////////////////////////////////
  36.  
  37. $ g++ --version
  38. g++ (GCC) 8.2.0
  39. Copyright (C) 2018 Free Software Foundation, Inc.
  40. This is free software; see the source for copying conditions.  There is NO
  41. warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  42.  
  43. $ g++ -std=c++17 minimal_example.cc
  44. $ ./a.out
  45. $
  46. $ clang++ --version
  47. clang version 6.0.0-1ubuntu2 (tags/RELEASE_600/final)
  48. Target: x86_64-pc-linux-gnu
  49. Thread model: posix
  50. InstalledDir: /usr/bin
  51.  
  52. $ clang++ -std=c++17 minimal_example.cc
  53. $ ./a.out
  54. $
  55. $
  56. $ clang++ -std=c++17 -stdlib=libc++ minimal_example.cc
  57. $ ./a.out
  58. custom allocate called!
  59. custom allocate called!
  60. custom allocate called!
  61. $
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement