fork download
  1. #include <deque>
  2. #include <memory>
  3. #include <iostream>
  4.  
  5. template<class T> class manager {
  6. static void construct(T* p, const T& val) {
  7. new((void*)p) T(val); }
  8. template<class U, class... Args>
  9. static void construct(U* p, Args&&... args) {
  10. new((void*)p) T(std::forward<Args>(args)...); }
  11. class allocator: public std::allocator<T> {
  12. public:
  13. void construct(T* p, const T& val) {
  14. manager::construct(p, val); }
  15. template<class U, class... Args>
  16. void construct(U* p, Args&&... args) {
  17. manager::construct(p, std::forward<Args>(args)...); }
  18. //needed for deque ...dunno why it is using rebind for T
  19. template<class U> struct rebind {
  20. typedef typename std::conditional<
  21. std::is_same<T,U>::value, allocator,
  22. std::allocator<U>>::type other; };
  23. };
  24. std::deque<T, allocator> storage; //deque preserves pointers
  25. public:
  26. template<class... Args>
  27. T* create(Args&&... args) {
  28. storage.emplace_back(std::forward<Args>(args)...);
  29. return &storage.back();
  30. }
  31. };
  32.  
  33. class special {
  34. friend class manager<special>;
  35. int i;
  36. special(int i): i(i) {}
  37. public:
  38. int get() const { return i; }
  39. };
  40.  
  41. int main() {
  42. manager<special> m;
  43. special* p = m.create(123);
  44. std::cout << p->get() << std::endl;
  45. }
  46.  
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
123