I usually use references instead of pointers when I want NULL
not to be possible. Since we can't have containers of references, what should be the type of a container that contains only non-null pointers?
As such, when the original pointers are deleted and they are set to nullptr , in the vector we'd know exactly about it. The only problem is that in C++ one cannot store references to pointers.
There isn't really such a thing as a null object instance, so you can't create a C++ reference to such a thing. In other languages a null reference is the equivalent of a C++ null pointer; it doesn't actually contain anything.
References cannot be null, whereas pointers can; every reference refers to some object, although it may or may not be valid. Note that for this reason, containers of references are not allowed. References cannot be uninitialized.
References are used to refer an existing variable in another name whereas pointers are used to store address of variable. References cannot have a null value assigned but pointer can. A reference variable can be referenced by pass by value whereas a pointer can be referenced but pass by reference.
If you were to use a container of pointers, you'd just use a container of pointers, don't place any NULL pointers in it, and move on.
However, you can still have a container of references if you use std::reference_wrapper
. For example:
#include <vector>
#include <iostream>
#include <functional>
int main()
{
int x = 5;
std::vector<std::reference_wrapper<int>> v;
v.push_back(std::reference_wrapper<int>(x));
x = 6;
std::cout << v[0]; // 6
}
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