fork(1) download
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. class Base
  5. {
  6. public:
  7. Base() = default;
  8. virtual ~Base() = default;
  9. virtual void run() = 0;
  10. };
  11.  
  12. class Derived1: public Base
  13. {
  14. public:
  15. Derived1() = default;
  16. ~Derived1() override = default;
  17. void run() override
  18. {
  19. std::cout << " Derived1";
  20. }
  21. };
  22.  
  23. class Derived2: public Base
  24. {
  25. public:
  26. Derived2() = default;
  27. ~Derived2() override = default;
  28. void run() override
  29. {
  30. std::cout << " Derived2";
  31. }
  32. };
  33.  
  34. // This function works but increase count
  35. void doGenericCopy(std::shared_ptr<Base> ptr)
  36. {
  37. ptr->run();
  38. std::cout << " Ref count: " << ptr.use_count() << std::endl;
  39. }
  40.  
  41. // This function works without increase count = OK !
  42. void doSpecificD1(std::shared_ptr<Derived1>& ptr)
  43. {
  44. ptr->run();
  45. std::cout << " Ref count: " << ptr.use_count() << std::endl;
  46. }
  47.  
  48. // Compilation error = FAILED !
  49. void doGeneric(std::shared_ptr<Base>& ptr)
  50. {
  51. ptr->run();
  52. std::cout << " Ref count: " << ptr.use_count() << std::endl;
  53. }
  54.  
  55. // Working fine for all Derivate = OK !
  56. template<typename CLASS>
  57. void doGenericTemplate(std::shared_ptr<CLASS>& ptr)
  58. {
  59. ptr->run();
  60. std::cout << " Ref count: " << ptr.use_count() << std::endl;
  61. }
  62.  
  63. void doClassic(Base& ptr)
  64. {
  65. ptr.run();
  66. std::cout << std::endl;
  67. }
  68.  
  69. int main()
  70. {
  71. auto d1 = std::make_shared<Derived1>();
  72. auto d2 = std::make_shared<Derived2>();
  73.  
  74. std::cout << "With copy: " << std::endl;
  75. doGenericCopy(d1);
  76. doGenericCopy(d2);
  77.  
  78. std::cout << "Specific: " << std::endl;
  79. doSpecificD1(d1);
  80.  
  81. std::cout << "Template: " << std::endl;
  82. doGenericTemplate(d1);
  83. doGenericTemplate(d2);
  84.  
  85. // Compilation issue
  86. //doGeneric(d1);
  87.  
  88. {
  89. std::cout << "Classic: " << std::endl;
  90. Derived1 c1;
  91. Derived2 c2;
  92. doClassic(c1);
  93. doClassic(c2);
  94. }
  95. }
  96.  
Success #stdin #stdout 0s 15248KB
stdin
Standard input is empty
stdout
With copy: 
  Derived1  Ref count: 2
  Derived2  Ref count: 2
Specific: 
  Derived1  Ref count: 1
Template: 
  Derived1  Ref count: 1
  Derived2  Ref count: 1
Classic: 
  Derived1
  Derived2