fork download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. template <typename Container>
  5. void f(Container& v)
  6. {
  7. std::cout << "f() v.data() " << v.data() << ", v.size() " << v.size() << '\n';
  8. for (int& n : v) n += 10;
  9. }
  10.  
  11. void g(std::vector<int>& v)
  12. {
  13. std::cout << "g() v.data() " << v.data() << ", v.size() " << v.size() << '\n';
  14. for (int& n : v) n += 100;
  15. }
  16.  
  17. int* p_;
  18.  
  19. struct My_alloc : std::allocator<int>
  20. {
  21.  
  22. My_alloc(int* p) { p_ = p; }// : p_(p) { }
  23.  
  24. template <class U, class... Args>
  25. void construct(U* p, Args&&... args) { std::cout << "My_alloc::construct(U* " << p << ")\n"; }
  26.  
  27. template <class U> void destroy(U* p) { std::cout << "My_alloc::destroy(U* " << p << ")\n"; }
  28.  
  29. pointer allocate(size_type n, std::allocator<void>::const_pointer hint = 0)
  30. {
  31. std::cout << "My_alloc::allocate() return " << p_ << "\n";
  32. return p_;
  33. }
  34. void deallocate(pointer p, size_type n) { std::cout << "deallocate\n"; }
  35.  
  36. template <typename U>
  37. struct rebind { typedef My_alloc other; };
  38.  
  39. // int* p_;
  40. };
  41.  
  42. int main()
  43. {
  44. std::vector<int> v = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
  45. std::cout << "main() v.data() " << v.data() << '\n';
  46. My_alloc my_alloc(&v[3]);
  47. std::vector<int, My_alloc> w(3, my_alloc);
  48. f(w);
  49. g(reinterpret_cast<std::vector<int>&>(w));
  50. for (int n : v) std::cout << n << ' ';
  51. std::cout << '\n';
  52. std::cout << "sizeof v " << sizeof v << ", sizeof w " << sizeof w << '\n';
  53. }
Success #stdin #stdout 0s 3276KB
stdin
Standard input is empty
stdout
main() v.data() 0x9d76008
My_alloc::allocate() return 0x9d76014
My_alloc::construct(U* 0x9d76014)
My_alloc::construct(U* 0x9d76018)
My_alloc::construct(U* 0x9d7601c)
f() v.data() 0x9d76014, v.size() 3
g() v.data() 0x9d76014, v.size() 3
0 1 2 113 114 115 6 7 8 9 
sizeof v 12, sizeof w 12
My_alloc::destroy(U* 0x9d76014)
My_alloc::destroy(U* 0x9d76018)
My_alloc::destroy(U* 0x9d7601c)
deallocate