1

Why is this code not working? There are two vectors. The base vector elements should refer to the derived vector elements as a reference (not a copy). The output is random numbers, so, for some reason, the reference_wrapper elements doesn't refer correctly to the derived elements but.

#include <iostream>
#include <vector>

struct Base
{
    Base (int a) : a_ (a) {}
    int a_;
};

struct DerivedA : Base
{
    DerivedA (int a) : Base (a) {}
};

int main(int argc, const char * argv[]) {
    std::vector <std::reference_wrapper <Base>> b;
    std::vector <DerivedA> d;

    const int num = 100;
    for (int i = 0; i < num; i++)
    {
        d.push_back (i);
        b.push_back (d.back());
    }

    for (int i = 0; i < num; i++)
        std::cout << b[i].get().a_;

    return 0;
}

1 Answers1

7

If you look into documentation of std::vector::push_back() it clearly says:

If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated.

Emphasis is mine. So this happens in your case, to fix it you need to make sure that capacity of your vector is big enough or use another container, which does not invalidate. For example std::deque

All iterators, including the past-the-end iterator, are invalidated. No references are invalidated.

Or store indexes of elements instead of references.

Slava
  • 43,454
  • 1
  • 47
  • 90