fork download
  1. #include <memory>
  2. #include <new>
  3. #include <cstdlib>
  4.  
  5. template<typename T, typename... Args>
  6. T*
  7. allocate(Args&&... args)
  8. {
  9. std::unique_ptr<T, void(*)(void*)> hold(static_cast<T*>(std::malloc(sizeof(T))),
  10. std::free);
  11. ::new (hold.get()) T(std::forward<Args>(args)...);
  12. return static_cast<T*>(hold.release());
  13. }
  14.  
  15. template<typename T>
  16. void
  17. deallocate(void* p)
  18. {
  19. static_cast<T*>(p)->~T();
  20. std::free(p);
  21. }
  22.  
  23. #include <iostream>
  24.  
  25. struct Base
  26. {
  27. int i;
  28. Base(int i) : i(i) {std::cout << "Base() " << i << std::endl ;}
  29. Base(const Base&) = delete;
  30. Base& operator=(const Base&) = delete;
  31. ~Base() {std::cout << "~Base() " << i << std::endl;}
  32.  
  33. virtual void bark() const {std::cout << "Hi Base! " << i << std::endl;}
  34. };
  35.  
  36. struct Derived
  37. : public Base
  38. {
  39. double d;
  40. Derived(int i, double d) : Base(i), d(d) {std::cout << "Derived() " << i << " " << d << std::endl;}
  41. Derived(const Base&) = delete;
  42. Derived& operator=(const Derived&) = delete;
  43. ~Derived() {std::cout << "~Derived() " << i << " " << d << std::endl;}
  44.  
  45. void bark() const {std::cout << "Hi Derived! " << i << " " << d << std::endl;}
  46. };
  47.  
  48. int
  49. main()
  50. {
  51. std::unique_ptr<Base, void(*)(void*)> p(allocate<Derived>(42, 10.42), deallocate<Derived>);
  52. p->bark();
  53. std::unique_ptr<Base, void(*)(void*)> p2 = std::move(p);
  54. p2->bark();
  55. }
  56.  
Success #stdin #stdout 0.01s 5340KB
stdin
Standard input is empty
stdout
Base() 42
Derived() 42 10.42
Hi Derived! 42 10.42
Hi Derived! 42 10.42
~Derived() 42 10.42
~Base() 42