After working 15 years in C++ I found that I don't understand references completely...
class TestClass { public: TestClass() : m_nData(0) { } TestClass(int n) : m_nData(n) { } ~TestClass() { cout << "destructor" << endl; } void Dump() { cout << "data = " << m_nData << " ptr = 0x" << hex << this << dec << endl; } private: int m_nData; }; int main() { cout << "main started" << endl; TestClass& c = TestClass(); c.Dump(); c = TestClass(10); c.Dump(); cout << "main ended" << endl; return 0; } // prints: // main started // data = 0 ptr = 0x0012FF54 // destructor // data = 10 ptr = 0x0012FF54 // main ended // destructor
I understand from this test, that TestClass instance is created on the stack (is this correct?) and initialized by first TestClass constructor. When this instance is allocated: when main function is loaded, or reference assignment is executed? When it is destroyed?
After second reference assignment object address is not changed. Does this mean that destructor and constructor are applied to the same memory area? Or memory is deallocated (dynamically? on the stack?) and allocated again?
I know everything about stack and heap-allocated objects lifetime, their constructors and destructors. But I cannot understand what exactly happens in this program.
Edit: Thanks to all. I tried to reproduce in this test some other (more complicated) program behavior. Your comments helped me to understand both my mistake and another program I am fighting with...
Fixed code is:
int main() { cout << "main started" << endl; TestClass t; TestClass& c(t); c.Dump(); c = TestClass(10); c.Dump(); cout << "main ended" << endl; return 0; }