fork(1) download
  1. #include <iostream>
  2. #include <memory>
  3. using namespace std;
  4.  
  5. class B {
  6. public:
  7. virtual void Bar() { cout << "B::Bar()"<<endl; }
  8. virtual ~B() { cout << "B destroyed"<<endl; }
  9. };
  10. class BB:public B{
  11. public:
  12. void Bar() override { cout << "BB::Bar()"<<endl; }
  13. ~BB() { cout << "BB destroyed"<<endl; }
  14. };
  15.  
  16. class A
  17. {
  18. private:
  19. unique_ptr<B> _b;
  20. public:
  21. template<class T>A(const T&b): _b(make_unique<T>(b)) { }
  22.  
  23. void Foo()
  24. {
  25. _b->Bar();
  26. }
  27. };
  28.  
  29. int main() {
  30. {
  31. B b;
  32. A a{b};
  33. a.Foo();
  34. }
  35. {
  36. BB bb;
  37. A aa{bb};
  38. aa.Foo();
  39. }
  40. return 0;
  41. }
Success #stdin #stdout 0s 4452KB
stdin
Standard input is empty
stdout
B::Bar()
B destroyed
B destroyed
BB::Bar()
BB destroyed
B destroyed
BB destroyed
B destroyed