fork(2) download
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. using std::shared_ptr;
  5. using std::weak_ptr;
  6. using std::make_shared;
  7.  
  8. class A : public std::enable_shared_from_this<A>
  9. {
  10. public:
  11.  
  12. class B{
  13. public:
  14. B(){}
  15. B(shared_ptr<A> ptr) { //??
  16. std::cout << "B()\n";
  17. ptrToA = ptr;
  18. }
  19. ~B(){}
  20. private:
  21. int bNumber{1};
  22. weak_ptr<A> ptrToA;
  23. };
  24.  
  25.  
  26. A(){ std::cout << "A() \n"; }
  27. ~A(){}
  28. shared_ptr<B> getPtrToB() { return ptrToB; }
  29.  
  30. void init(){ //Передвинул из конструктора сюда
  31. ptrToB = make_shared<B>(shared_from_this());
  32. }
  33.  
  34. private:
  35. shared_ptr<B> ptrToB;
  36. int aNumber{0};
  37. };
  38.  
  39. int main(){
  40. A aInstance;
  41. std::cout << "A created \n";
  42. aInstance.init();
  43. std::cout << "Init Finished \n";
  44. return 0;
  45. }
Runtime error #stdin #stdout #stderr 0s 4368KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
terminate called after throwing an instance of 'std::bad_weak_ptr'
  what():  bad_weak_ptr