I’ve always been a bit confused about how STL containers (vector, list, map…) store values. Do they store references to the values I pass in, or do they copy/copy construct +store the values themselves?
For example,
int i;
vector<int> vec;
vec.push_back(i);
// does &(vec[0]) == &i;
and
class abc;
abc inst;
vector<abc> vec;
vec.push_back(inst);
// does &(vec[0]) == &inst;
Thanks
STL Containers copy-construct and store values that you pass in. If you want to store objects in a container without copying them, I would suggest storing a pointer to the object in the container:
This is the most logical way to implement the container classes to prevent accidentally storing references to variables on defunct stack frames. Consider:
Storing a reference to
iwould be dangerous as you would be referencing the memory location of a local variable after returning from the method in which it was defined.