Consider the following code:
#include <iostream>
#include <vector>
using namespace std;
class SomeClass {
public:
SomeClass(int num) : val_(num) {}
int val_;
int val() const { return val_; }
};
// Given a vector of vector of numbers, this class will generate a vector of vector of pointers
// that point to SomeClass.
class Generator {
public:
vector<SomeClass> objects_;
vector<vector<SomeClass*> > Generate(const vector<vector<int> >& input) {
vector<vector<SomeClass*> > out;
for (const auto& vec : input) {
out.push_back({});
for (const int num : vec) {
SomeClass s(num);
objects_.push_back(s);
out.back().push_back(&objects_.back());
}
}
return out;
}
};
int main() {
Generator generator;
auto output = generator.Generate({{2, 3}, {4, 5}, {6}});
for (const auto& vec : output) {
for (const auto* obj : vec) {
printf("%d ",obj->val());
}
printf("\n");
}
return 0;
}
The Generate
method in the Generator
class will simply convert the vector of vector of int
s to a vector of vector of pointers to SomeClass
.
SomeClass
is simply a container for a simple int
value with a getter method.
I would expect the following output:
2 3
4 5
6
However, I get the following output:
junk_integer junk_integer
4 5
6
It seems the pointers in the first row become dangling pointers. What is wrong with this code?