Can anyone make me clear what these lines of code are doing? Is the value of m being copied to the memory location of n
? Or n
is also pointing to the same address as m
? And how?
int m=5;
int &n=m;
CodePudding user response:
int m = 5;
This line creates a variable of type int
which contains the value 5
.
int& n = m;
This line creates a reference to m
. You can think of it as an alias to m
. So this instruction :
n = 6;
Actually changes the value of m
.
References are typically (not always though, see here) implemented as pointers internally. The compiler will typically reserve a location in memory where it will store the memory adress of m
. This means that the following pieces of code are equivalent:
int main() {
int m = 5;
int& n = m; // Reference
n = 6;
}
int main() {
int m = 5;
int* const n = &m; // Pointer const (meaning the held memory address
// can't be changed, only the value at that address can be)
*n = 6;
}
I personally only use const
references, meaning I can't modify the value of the values that is being referenced. When I actually want to modify the referenced value, I use pointers because I think they provide more clarity (they basically say "I'm not owning this value, which means that when I modify it, expect a value somewhere else in the program to have changed.").
So when to use const
references? Arguably their most frequent use case is passing a function argument by reference. For example, passing a std::string
object to the following function actually copies it, which can be very expensive for large objects.
#include <string>
void doStuffWithString(std::string str /* potentially expensive */) {
// ...
}
Instead, you can pass it by const
reference, meaning you don't pass the actual object to the function, but a const
reference to it to prevent the unnecessary copy.
#include <string>
void doStuffWithString(const std::string& str /* not expensive */) {
// ...
}
If I ever want to modify the value of the object being passed, I pass it by address (with a pointer).
#include <string>
void modifyString(std::string* str /* pointer */) {
// ...
}
int main() {
std::string hiMom("Hi mom!");
modifyString(&hiMom); // Explicitly shows the caller that we're passing
// a pointer, meaning the value of hiMom might change
return 0;
}
CodePudding user response:
int m = 5;
The above line makes a new variable of type int
and assigns it the value 5
.
int &n = m;
This makes a reference variable of type int
and assigns m
to it. This means that n
is basically another name for m
, and if n
's value is changed, m
's value will change as well. It's kinda like pointers
, but way more high level than pointers
.