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