![]() |
VOOZH | about |
In C++, the Standard Template Library (STL) provides a robust and versatile collection of containers, with std::vector being one of the most commonly used. However, you may encounter an obstacle when trying to create a vector of references.
In this article, we are going to look at why you cannot make a vector of references and some ways around it to do approximately the same thing.
There are 3 major reasons why vectors can't store references in C++:
Unlike pointers, references must always be initialized to refer to a valid object. std::vector requires elements to be default-constructible because it may need to resize or move elements, which could lead to situations where elements are temporarily uninitialized or invalidāsomething not permissible for references.
References in C++ cannot be reseated to refer to another object. However, std::vector manages its elements dynamically, which involves copying or moving elements around in memory during resizing operations. This behaviour conflicts with the nature of references, which must stay bound to their initial object.
When std::vector resizes, it reallocates memory and moves elements to a new location. This operation would invalidate references because references cannot point to a different memory location post-initialization.
While you can't store references directly in a std::vector, there are several alternative approaches to achieve similar functionality:
You can use pointers instead of the references. Pointers can be stored in a vector and point to any permissive object of memory. You must be able to manage the lifespan of the objects pointed to in these pointers to avoid the creation of a dangling pointer.
10 20 30
The STL provides std::reference_wrapper, which can be used to store references in STL containers. std::reference_wrapper is a utility that allows references to be stored in standard containers like std::vector.
10 20 30
Smart pointers such as std::shared_ptr and std::unique_ptr can also be used to maintain the lifetime of objects in a way such that it minimizes memory leaks and dangling pointers. They are safer options than the raw pointers.
10 20 30
Although you cannot directly create a vector of references in C++, understanding the reasons behind this restriction lets you pick the right alternative. Using pointers, std::reference_wrapper, or smart pointers gives the flexibility needed for working around this limitation but still in line with the design principles of C++ and the STL.