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