fork download
  1. template <typename T>
  2. T* dup(T* begin, T* end)
  3. {
  4. class mem_guard {
  5. void *p;
  6. public:
  7. mem_guard(std::size_t n) { p = std::malloc(n*sizeof(T)); }
  8. ~mem_guard() { if (p) std::free(p); }
  9.  
  10. T* get() { return static_cast<T*>(p); }
  11. T* release() { T *ptr=get(); p=0; return ptr; }
  12. };
  13.  
  14. class unroll_guard {
  15. T *start, *curr;
  16. public:
  17. unroll_guard(T *p) : start(p), curr(p) {}
  18. ~unroll_guard() { if (start) while (curr-- != start) curr->~T(); }
  19. void emplace_back(T const& t) { new (curr) T(t); ++curr; }
  20. void release() { start = 0; }
  21. };
  22.  
  23. std::ptrdiff_t n = end - begin;
  24. assert(n > 0);
  25.  
  26. // guard the memory
  27. mem_guard memory(n);
  28. if (!memory.get())
  29. return 0;
  30.  
  31. // guard the items
  32. unroll_guard data(memory.get());
  33. for (; begin != end; ++begin)
  34. data.emplace_back(*begin);
  35.  
  36. // everything ok, release the resources
  37. data.release();
  38. return memory.release();
  39. }
  40.  
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty