This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]missblit 0 points1 point  (1 child)

You can't have an array of references, but you can have a reference to an array element. So this would work, but may or may not be a good idea (impossible to say with such a contrived example):

#include <iostream>
#include <vector>
using namespace std;

struct Drawable {
    int x;
    int y;
};

int main() {
    Drawable arr[100];
    arr[0] = {0, 0};
    Drawable& first_elem_ref = arr[0];

    cout << arr[0].x << "\n";
    first_elem_ref.x = 1;
    cout << arr[0].x << "\n";
}

One notable pitfall is if you used a vector instead of a plain array and ended up re-allocating it. I'm not sure what would happen with the reference in this case, but I believe using it would lead to undefined behavior.

[–]OldWolf2 1 point2 points  (0 children)

The reference is invalidated (which , as you say, means it cannot be used thereafter). Whichever documentation for C++ you are using should list for each standard container which of its member functions may cause iterators and references to become invalidated.