+ 3
what is the (technical) difference between a pointer variable (<datatype>*) and a reference variable (<datatype>&). which one should be preferred?
2 Respuestas
+ 1
Hi multimodcrafter, thanks for the awesome question! :-)
From a programming point of view there's a difference. From a low-level technical perspective as in machine code there's very likely none.
Therefore the main difference in my opinion is how error prone both ways of passing variables are.
Pointers are a more general way because they can point to any memory address you want to.
For references you have to put an object in the call so the reference passed cannot be a null pointer.
Here's an example of a definition and a call to a function that passes a pointer or a reference respectively:
void func(int* a) { }
void func2(int& a) { }
int main() {
func(&a);
func(static_cast<int*>(0));
func2(a);
return 0;
}
In my opinion the call to func2 is "cleaner" as it does not require the explicit "&" and avoids having null pointers (for which you should check in the code of "func", making this variant even more bloated).
0
thank you very much Stefan! now I fully understand :)