1

I'm a c++ beginner, I want to initialize an array so that the element of the array is actually a reference to a variable.

string string_1;
string string_2;
string strings[2] = {&string_1, &string_2};

Is this allowed? So any operation done to the array will be applied to the variables string_1 and string_2 themselves?

Pransh Tiwari
  • 3,983
  • 1
  • 32
  • 43
PowerLove
  • 303
  • 8
  • 25

1 Answers1

3

You can simulate an array of references:

using s_ref = std::reference_wrapper<std::string>;
s_ref strings[] = { std::ref(string_1), std::ref(string_2) };

Or just use pointers (that's really what reference_wrapper does underneath).

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458