Monday, August 20, 2018

pass by reference - Use of the & operator in C++ function signatures



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




int* ptr=#


means that ptr now holds the address to num, but what does that mean?



void DoSomething(string& str)


from what I understand that is a pass by reference of a variable (which means passing the address) but when I do




void DoSomething(string& str)
{
string copy=str;
}


what it creates is a copy of str. What I thought it would do is raise an error since I'm trying to assign a pointer to a variable.



What is happening here? And what is the meaning of using * and & in function calls?


Answer




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.

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...