Creating an Array of References

Is it possible to create an array of references in C++?

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.

Using 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.

Using Pointers

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.

References

This lesson introduces references, explaining how they work, their benefits, and their role in performance and data manipulation

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Swapping Values Using References
How can I use references to swap the values of two variables without using a temporary variable?
References and Runtime Polymorphism
Can I use references with polymorphic classes to achieve runtime polymorphism?
Implementing Observer Pattern with References
How can I use references to implement a simple observer pattern in C++?
Reference vs Pointer to Const
What's the difference between a reference and a pointer to const in terms of function parameters?
Dangers of Returning References to Local Objects
What are the implications of returning a reference from a function that creates a local object?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant