fork download
  1. #include <iostream>
  2.  
  3. class IdProvider {
  4. static int count;
  5. private:
  6. IdProvider(){}
  7. public:
  8. static IdProvider& Instance() {
  9. static IdProvider instance;
  10. return instance;
  11. }
  12.  
  13. int Next() {
  14. return ++count;
  15. }
  16. };
  17.  
  18. int IdProvider::count = 0;
  19.  
  20. template <typename T> class TracingValue {
  21.  
  22. private:
  23. T m_Val;
  24. int m_Id;
  25.  
  26. private:
  27. void LogStackTrace() {}
  28.  
  29. public:
  30. int Id() const { return m_Id; }
  31.  
  32. TracingValue &operator=(const TracingValue &other) {
  33. LogStackTrace();
  34. m_Val = other.m_Val;
  35. std::cout << "id: " << this->Id() << " new value: " << m_Val
  36. << " from id: " << other.Id() << std::endl;
  37. return *this;
  38. }
  39.  
  40. TracingValue &operator=(const T &val) {
  41. LogStackTrace();
  42. m_Val = val;
  43. std::cout << "id: " << this->Id() << " new value: " << m_Val << std::endl;
  44. return *this;
  45. }
  46.  
  47. TracingValue(const T &val):m_Id(IdProvider::Instance().Next()),m_Val(val) {
  48. std::cout << "id: " << this->Id() << " constructed with value: " << val << std::endl;
  49. LogStackTrace();
  50. }
  51.  
  52. TracingValue(const TracingValue &other):TracingValue(other.m_Val) {
  53. std::cout << "id: " << this->Id() << " constructed from id: " << other.Id() << std::endl;
  54. }
  55.  
  56. TracingValue():TracingValue(T()) { LogStackTrace(); }
  57.  
  58. operator T() const { return m_Val; }
  59. };
  60.  
  61. int main() {
  62. TracingValue<double> d;
  63. d = 3.;
  64. d = 42.;
  65. double x = d - 2.;
  66. std::cout << x << std::endl;
  67. TracingValue<double> other_d(d);
  68.  
  69. TracingValue<double> another_d;
  70. another_d = other_d;
  71. }
  72.  
Success #stdin #stdout 0s 3344KB
stdin
Standard input is empty
stdout
id: 1 constructed with value: 0
id: 1 new value: 3
id: 1 new value: 42
40
id: 2 constructed with value: 42
id: 2 constructed from id: 1
id: 3 constructed with value: 0
id: 3 new value: 42 from id: 2