fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. class A {
  6. public:
  7. int num = 0;
  8. A* parent = nullptr;
  9.  
  10. A(){ cout << "A created: " << this << endl; }
  11.  
  12. A(const A &s) : num(s.num), parent(s.parent)
  13. {
  14. cout << "A copied: " << &s << " -> " << this << endl;
  15. }
  16.  
  17. ~A(){ cout << "A destroyed: " << this << endl; }
  18.  
  19. vector<A> foo(A &a)
  20. {
  21. A a1;
  22. a1.num = a.num;
  23. a1.parent = &a;
  24.  
  25. vector<A> list;
  26. list.reserve(1);
  27. list.push_back(a1);
  28.  
  29. A &temp = list.front();
  30.  
  31. cout << "(foo) temp.parent: " << temp.parent << ", num: " << temp.parent->num << endl;
  32.  
  33. return list;
  34. }
  35. };
  36.  
  37. int main()
  38. {
  39. A a;
  40. a.num = 2;
  41.  
  42. vector<A> list = a.foo(a);
  43.  
  44. A &temp = list.front();
  45.  
  46. cout << "(main) temp.parent: " << temp.parent << ", num: " << temp.parent->num << endl;
  47.  
  48. return 0;
  49. }
Success #stdin #stdout 0.01s 5388KB
stdin
Standard input is empty
stdout
A created: 0x7ffd7319e8b0
A created: 0x7ffd7319e850
A copied: 0x7ffd7319e850 -> 0x556ccff0fe80
(foo) temp.parent: 0x7ffd7319e8b0, num: 2
A destroyed: 0x7ffd7319e850
(main) temp.parent: 0x7ffd7319e8b0, num: 2
A destroyed: 0x556ccff0fe80
A destroyed: 0x7ffd7319e8b0