fork download
  1. #include <iostream>
  2. #include <memory>
  3. #include <queue>
  4.  
  5. using namespace std;
  6.  
  7. class Base {
  8. public:
  9. Base() = default;
  10. virtual ~Base() = default;
  11. virtual void run() = 0;
  12. };
  13.  
  14. class Derived1: public Base {
  15. public:
  16. Derived1() = default;
  17. virtual ~Derived1() = default;
  18. void run() { cout << "Derived1" << endl; }
  19. };
  20.  
  21. class Derived2: public Base {
  22. public:
  23. Derived2() = default;
  24. virtual ~Derived2() = default;
  25. void run() { cout << "Derived2" << endl; }
  26. };
  27.  
  28. void doSomething(std::shared_ptr<Base> ptr) {
  29. cout << "Ptr: " << typeid(ptr).name() << endl;
  30. cout << "Obj: " << typeid(*ptr).name() << endl;
  31. ptr->run();
  32. }
  33.  
  34. void copyPtr(const std::shared_ptr<Base>& in, std::shared_ptr<Base>& out)
  35. {
  36. std::queue<std::shared_ptr<Base>> q;
  37.  
  38. q.push(in);
  39. out = q.front();
  40. q.pop();
  41. }
  42.  
  43. int main() {
  44. std::shared_ptr<Base> ptr;
  45.  
  46. doSomething(std::make_shared<Derived1>());
  47. doSomething(std::make_shared<Derived2>());
  48.  
  49. copyPtr(std::make_shared<Derived1>(), ptr);
  50. doSomething(ptr);
  51. copyPtr(std::make_shared<Derived2>(), ptr);
  52. doSomething(ptr);
  53. }
  54.  
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
Ptr: St10shared_ptrI4BaseE
Obj: 8Derived1
Derived1
Ptr: St10shared_ptrI4BaseE
Obj: 8Derived2
Derived2
Ptr: St10shared_ptrI4BaseE
Obj: 8Derived1
Derived1
Ptr: St10shared_ptrI4BaseE
Obj: 8Derived2
Derived2