From what I know, references are just another name for a variable whilst pointers are their own variable. Pointers take up space. People often say "use a reference or pointer" but they don't say which is better. If references take up no memory of their own, then references win in that department. What I don't know is if the compiler makes a distinction between references and normal variable. If you do operations on a reference, does it compile to the same code as normal variable?
References are usually preferred over pointers whenever you don't need “reseating”. This usually means that references are most useful in a class's public interface. References typically appear on the skin of an object, and pointers on the inside.
Pointers save memory space. Execution time with pointers is faster because data are manipulated with the address, that is, direct access to memory location. Memory is accessed efficiently with the pointers.
As a rule of thumb, passing by reference or pointer is typically faster than passing by value, if the amount of data passed by value is larger than the size of a pointer.
If you have a pointer (or a reference) to data, then you have two levels of memory access. First to load an address from the pointer (or reference) and then second to actually load the data. If you simply directly reference a variable, there is only one level of memory access. So here, a variable is faster.
Internally references are also implemented in terms of pointer. So, it's difficult to say which is faster pointer/reference.
It's a usage of these two which makes a difference.
For example you want to pass by reference a parameter to the function.
void func(int& a) case_1
{
//No need to check for NULL reference...
}
void func(int* a) case_2
{
//Need o check if pointer is not NULL
}
In case_2 you have to explicitly check if pointer is not NULL before dereferncing it whereas that's not the case with references because references are initialized to something.
Assumption is that you are playing game in civilized manner i.e
You are not doing something like:-
int*p = NULL;
int &a = *p;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With