I have a loop which I create a unique_ptr in and move it into a vector. I also need to store it in another vector so I store a reference of it in another vector using the end()
method of the first vector.
For some reason I happen to have some invalid read errors which seem to affect the element before the last one of the list containing the references.
Here is a simple snippet to illustrate my sayings:
#include <iostream>
#include <memory>
#include <vector>
int main(void)
{
std::vector<std::unique_ptr<int>> other;
std::vector<std::reference_wrapper<std::unique_ptr<int>>> vec;
for (int it = 0; it < 2; ++it)
{
std::unique_ptr<int> ptr = std::make_unique<int>(it);
other.push_back(std::move(ptr));
vec.push_back(*(other.end() - 1));
}
for (auto &it : vec)
std::cout << "Vec: " << *it.get() << std::endl;
return 0;
}
This will output something like that:
$ ./a.out
Vec: 35716160
Vec: 1
As you can see the first element holds garbage, I suspect pushing from the end()
of the first vector causes the issue, but I can't seem to figure why.