I think I am struggling with an issue similar to this one: C++ std::vector::size() changes its state but am unable to make the connection to my current issue.
I am seeking to create a vector of pointers to objects. This is done because I wish to create a subset to a larger collection of objects to operate on. My code is
mp::CellSet generate_1D_cellset(geom::NodeSet &nodes){
/*Generate cells from an (ordered in terms of position) list of 1D nodes*/
std::vector<mp::Cell*> cell_array;
cell_array.resize(nodes.number-1);
std::string name = "Linear1D";
for(int i=0; i<(nodes.number-1); i++){
//std::cout << i;
cell_array[i] = generate_1D_cell(i,name,nodes);
}
mp::CellSet cells = mp::CellSet(cell_array);
return cells;
}
when I query (using gdb) cell_array.size()
immediately after creation or after the resize I get the answer I expect (2 for my test problem) but if I query the same response at the beginning of the for loop I find that cell_array.size()
gives a very unexpected value (very large).
Why does the length of the vector change? Is the pointer to the Cell object going out of scope somehow?