fork download
  1. #include <iostream>
  2.  
  3. class A
  4. {
  5. public:
  6. A(int& x) : m_x(x) {}
  7. const int& getX() const { return m_x; }
  8. void DecrX() { --m_x; }
  9. void print() { std::cout << "A::m_x= " << m_x << std::endl << std::endl; }
  10. private:
  11. int& m_x;
  12. };
  13.  
  14. A calculateStuffAndReturnAnAForMe(int x, int y)
  15. {
  16. int z = x + y;
  17. A a(z);
  18. return a;
  19. }
  20.  
  21. int main()
  22. {
  23. A badData = calculateStuffAndReturnAnAForMe(5, 10);
  24. badData.print(); // badData's m_x is a reference to z, which is no-longer valid.
  25. std::string input;
  26. std::cout << "Enter your name: ";
  27. std::cin >> input;
  28. std::cout << std::endl << "You entered: " << input << std::endl;
  29. badData.print();
  30. }
Success #stdin #stdout 0s 3476KB
stdin
Oliver
stdout
A::m_x= -1217052684

Enter your name: 
You entered: Oliver
A::m_x= 142901316