Use of the & operator in C++ function signatures

后端 未结 9 971
刺人心
刺人心 2020-11-29 00:36

I\'m currently reading through Accelerated C++ and I realized I don\'t really understand how & works in function signatures.

int* ptr=#
         


        
9条回答
  •  难免孤独
    2020-11-29 01:23

    A reference is not a pointer, they're different although they serve similar purpose. You can think of a reference as an alias to another variable, i.e. the second variable having the same address. It doesn't contain address itself, it just references the same portion of memory as the variable it's initialized from.

    So

    string s = "Hello, wordl";
    string* p = &s; // Here you get an address of s
    string& r = s; // Here, r is a reference to s    
    
    s = "Hello, world"; // corrected
    assert( s == *p ); // this should be familiar to you, dereferencing a pointer
    assert( s == r ); // this will always be true, they are twins, or the same thing rather
    
    string copy1 = *p; // this is to make a copy using a pointer
    string copy = r; // this is what you saw, hope now you understand it better.
    

提交回复
热议问题