samedi 18 juillet 2015

Will a vector move if I don't call push_back?

I'm working with a function that takes as input an array of structures of the form

struct Info
{
  const char* something;
  // more stuff
};

Since I didn't want to worry about cleaning up the memory in the char*, my thinking was that I'd

  1. Create a std::vector<std::string> of all the something
  2. loop over the vector and create the Info structures using std::vector::c_str()
  3. feed the structures to the function.

That way the vector owns all the strings and I don't have to worry about memory management. My only concern is that the vector could decide to move the strings in memory at some point, which would invalidate the pointers I'm getting from c_str().

So my question: assuming I don't add anything to the vector, can I count on the pointers to stay where they are? As a bonus, can I combine steps 1 and 2 into a single loop assuming I call reserve before so that the vector doesn't have to move?

Aucun commentaire:

Enregistrer un commentaire