I always have the impression that I shouldn't use reference to initialize class member because
- I don't know the lifetime of the reference and
- If the reference value changes outside the class, the corresponding class member would also change to the new value.
But after testing the following code, I am confused...
class Test { public: Test(int& i) :m_i(i) {} int m_i; }; class Test3 { public: Test3(int& i) :m_i(i) {} const int& m_i; }; int main() { { std::cout << "\n// Test 1" << std::endl; int i = 10; Test oTest(i); printf("oTest.i = %d\n", oTest.m_i); i = 20; printf("oTest.i = %d\n", oTest.m_i); } { std::cout << "\n// Test 1.1" << std::endl; int* i = new int; *i = 10; Test oTest(*i); printf("oTest.i = %d\n", oTest.m_i); *i = 20; printf("oTest.i = %d\n", oTest.m_i); delete i; printf("oTest.i = %d\n", oTest.m_i); } { std::cout << "\n// Test 3" << std::endl; int i = 10; Test3 oTest(i); printf("oTest.i = %d\n", oTest.m_i); i = 20; printf("oTest.i = %d\n", oTest.m_i); } { std::cout << "\n// Test 3.1" << std::endl; int* i = new int; *i = 10; Test3 oTest(*i); printf("oTest.i = %d\n", oTest.m_i); *i = 20; printf("oTest.i = %d\n", oTest.m_i); delete i; printf("oTest.i = %d\n", oTest.m_i); } return 0; } Output is as follows:
// Test 1 oTest.i = 10 oTest.i = 10 <---- Why not 20? // Test 1.1 oTest.i = 10 oTest.i = 10 <---- Why not 20? oTest.i = 10 <---- Why not some garbage number? // Test 3 oTest.i = 10 oTest.i = 20 // Test 3.1 oTest.i = 10 oTest.i = 20 oTest.i = 20 <---- Why not some garbage number? Thanks very much for your comment.