I have an object called LastQueryInfo lastQuery in my class. Every time this object changes, I add it to a vector called history.
Initially, when I did history.push_back(lastQuery) I didn’t know what would happen – is the vector going to make a copy of the object? or is it going to keep a reference to it? So if later I modify lastQuery, are all the objects (assuming they are references) in the history vector going to be modified?
After some testing, I found that history.push_back(lastQuery) is indeed going to make a copy of the object, then add it to the vector. But how can I know that without doing any tests? How can I know when C++ is going to make a copy, and when it’s going to add the actual object?
std::vectoralways stores a copy† of whatever youpush_back(). So modifying the value you passed in will not affect the value stored in the vector. It isn’t like Java or C# where anObject o;is actually a reference to the object, and the object lives until the garbage collector comes and picks it up when the last reference to it goes away. In C++,Object o;is the actual object, which will go away at the end of its scope.So if
std::vectoronly stores references to the objects youpush_back(), then it will be utterly useless for things like this:Since
numberwill go away at the end of the loop,numberswould hold references to something that will not exist ifstd::vectorwas implemented by storing only references. Ifstd::vectoractually stored the values, you could access them even after the loop.† C++11 supports move semantics, so if the thing you’re pushing back is actually a temporary that will go away soon, it’ll move the internals of the object into the vector storage instead of copying. You can also explicitly use C++11’s
std::move()to “force” the move duringpush_back(). But vector will copy the value in every other case. It’s an implementation detail to optimize the performance of vectors.