Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Container of references / non-nullable pointers

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?

like image 661
GreyGeek Avatar asked Jan 18 '13 18:01

GreyGeek


People also ask

Can you store references C++?

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.

What is there is no null reference?

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.

Can C++ references be null?

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.

Why are references different from pointers?

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.


1 Answers

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
}

Live demo

like image 80
Lightness Races in Orbit Avatar answered Oct 11 '22 12:10

Lightness Races in Orbit