Creating an array of references in C++ is not directly possible. This is because references must be initialized when they are created and cannot be reseated (made to refer to a different object) later. However, there are a few workarounds that can achieve similar functionality.
std::reference_wrapper
The most common and recommended approach is to use std::reference_wrapper
from the <functional>
header. This class template wraps a reference in a copyable, assignable object:
#include <array>
#include <functional>
#include <iostream>
int main() {
int a{1}, b{2}, c{3};
std::array<
std::reference_wrapper<int>, 3
> refArray{a, b, c};
for (auto& ref : refArray) {
std::cout << ref << ' ';
ref.get()++; // Modify the original values
}
std::cout << '\n';
std::cout << "a: " << a
<< ", b: " << b
<< ", c: " << c << '\n';
}
1 2 3
a: 2, b: 3, c: 4
In this example, we create an array of std::reference_wrapper<int>
. We can access and modify the original values through this array.
Another approach is to use an array of pointers. While not exactly the same as references, pointers can achieve similar functionality:
#include <array>
#include <iostream>
int main() {
int a{1}, b{2}, c{3};
std::array<int*, 3> ptrArray{&a, &b, &c};
for (auto ptr : ptrArray) {
std::cout << *ptr << ' ';
(*ptr)++;
}
std::cout << '\n';
std::cout << "a: " << a
<< ", b: " << b
<< ", c: " << c << '\n';
}
1 2 3
a: 2, b: 3, c: 4
This approach uses pointers instead of references, but achieves a similar result.
Remember, while these methods allow you to create collections of references or reference-like objects, they each have their own implications for syntax and semantics. The std::reference_wrapper
approach is generally preferred as it more closely mimics the behavior of actual references.
Answers to questions are automatically generated and may not have been reviewed.
This lesson demystifies references, explaining how they work, their benefits, and their role in performance and data manipulation
Comprehensive course covering advanced concepts, and how to use them on large-scale projects.
View Course