0

I always have the impression that I shouldn't use reference to initialize class member because

  1. I don't know the lifetime of the reference and
  2. 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.

1 Answer 1

1

Your Test(int& i) :m_i(i) invokes a copy constructor, and since your field is an int, not an int&, test 1 and 1.1 always print the original 10.

In Test 3.1, there is no requirement that accessing memory that has been freed/deleted with yields garbage. (There are debugging compilers that deliberately put a distinct pattern in the freed memory, but that is part of their debugging nature.) Nothing in your toy program changes the value that was pointed to by i, so you "get away with it". In an enterprise program, you will get a hard-to-find "Heisenbug".

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.