fork download
  1. #include <iostream>
  2. #include <memory>
  3.  
  4.  
  5. namespace myns
  6. {
  7.  
  8. class Base
  9. {
  10. public:
  11.  
  12. Base() = default;
  13. virtual ~Base() = default;
  14.  
  15. virtual void Create()
  16. {
  17. std::cout << "Created in Base" << std::endl;
  18. }
  19.  
  20. virtual void Destroy()
  21. {
  22. std::cout << "Destroyed in Base - " << std::endl;
  23. }
  24. };// class Base
  25.  
  26. class ADerivded : public Base
  27. {
  28. public:
  29.  
  30. void Create() override
  31. {
  32. std::cout << "Created in ADerivded" << std::endl;
  33. }
  34.  
  35. void Destroy() override
  36. {
  37. std::cout << "Destroyed in ADerivded" << std::endl;
  38. }
  39.  
  40. };// class ADerivded
  41.  
  42. template<typename T>
  43. void unmake(T* ptr)
  44. {
  45. ptr->Destroy();
  46. delete ptr;
  47. }
  48.  
  49. template<typename T, typename... Arguments>
  50. std::shared_ptr<T> make(Arguments&&... args)
  51. {
  52. std::shared_ptr<T> ptr = std::shared_ptr<T>(new T(), myns::unmake<T>);
  53. ptr->Create(std::forward<Arguments>(args)...);
  54. return ptr;
  55. }
  56.  
  57. }//namespace myns
  58.  
  59. using namespace std;
  60.  
  61. int main()
  62. {
  63. shared_ptr<myns::ADerivded> a = myns::make<myns::ADerivded>();
  64.  
  65. return 0;
  66. }
  67.  
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Created in ADerivded
Destroyed in ADerivded