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. auto p = static_cast<T*>(hold.release());
  14. std::cout << "allocating p:" << p << std::endl;
  15. return p;
  16. }
  17.  
  18. template<typename T>
  19. void
  20. deallocate(void* p)
  21. {
  22. std::cout << "freeing p:" << p << std::endl;
  23. static_cast<T*>(p)->~T();
  24. std::free(p);
  25. }
  26.  
  27. #include <iostream>
  28.  
  29. struct Base
  30. {
  31. int i;
  32. Base() {std::cout << "Base()\n";}
  33. Base(const Base&) = delete;
  34. Base& operator=(const Base&) = delete;
  35. ~Base() {std::cout << "~Base()\n";}
  36. };
  37.  
  38. struct Derived
  39. : public Base
  40. {
  41. int ii;
  42. Derived() {std::cout << "Derived()\n";}
  43. Derived(const Base&) = delete;
  44. Derived& operator=(const Derived&) = delete;
  45. virtual ~Derived() {std::cout << "~Derived()\n";}
  46.  
  47. void bark() const {std::cout << "Hi Derived!\n";}
  48. };
  49.  
  50. int
  51. main()
  52. {
  53. Derived *pd = new Derived();
  54. std::cout << "pd:" << pd << std::endl;
  55. Base *pb = pd;
  56. std::cout << "pb:" << pb << std::endl;
  57. void * pv = pb;
  58. std::cout << "pv:" << pv << std::endl;
  59. Derived *pd2 = static_cast<Derived*>(pv);
  60. std::cout << "pd:" << pd2 << std::endl;
  61. std::cout << "all at once:" << static_cast<Derived*>(static_cast<void*>(static_cast<Base*>(pd))) << std::endl;
  62.  
  63. std::unique_ptr<Derived, void(*)(void*)> p(allocate<Derived>(), deallocate<Derived>);
  64. p->bark();
  65. std::unique_ptr<Base, void(*)(void*)> p2 = std::move(p);
  66. }
Runtime error #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
Base()
Derived()
pd:0x9890008
pb:0x989000c
pv:0x989000c
pd:0x989000c
all at once:0x989000c
Base()
Derived()
allocating p:0x9890018
Hi Derived!
freeing p:0x989001c