fork download
  1. #include <iostream>
  2. #include <memory>
  3. using namespace std;
  4.  
  5. template <typename T>
  6. struct Destroy {
  7. void operator()(T *t) const {
  8. t->destroy();
  9. }
  10. };
  11.  
  12. class IRuntime {
  13. public:
  14. virtual ~IRuntime() = default;
  15. virtual void destroy() = 0;
  16. };
  17.  
  18. class IRuntimeImpl : public IRuntime {
  19. public:
  20. IRuntimeImpl() {
  21. cout << "created " << this << endl;
  22. }
  23.  
  24. ~IRuntimeImpl() override {
  25. cout << "destroyed " << this << endl;
  26. }
  27.  
  28. void destroy() override {
  29. delete this;
  30. }
  31. };
  32.  
  33. IRuntime* createIRuntime() {
  34. return new IRuntimeImpl;
  35. }
  36.  
  37. class Test {
  38.  
  39. std::unique_ptr<IRuntime, Destroy<IRuntime>> runtime;
  40.  
  41. public:
  42. Test() : runtime(createIRuntime()) {
  43. }
  44. };
  45.  
  46. int main() {
  47. std::unique_ptr<IRuntime, Destroy<IRuntime>> runtime(createIRuntime());
  48. Test{};
  49. return 0;
  50. }
Success #stdin #stdout 0s 5508KB
stdin
Standard input is empty
stdout
created 0x55ea9da49e70
created 0x55ea9da4aea0
destroyed 0x55ea9da4aea0
destroyed 0x55ea9da49e70