2

This one is pretty basic.

I remember seeing a warning somewhere (I can't find it now) to the effect that you shouldn't directly modify the contents of STL containers, because it might play havoc with the internal record-keeping the container does. From that, it followed that you should use something like boost's ptr_containers whenever you had an element you want modify.

This is essentially all I want to do:

int main (int argc, char *argv[]) {
    std::vector<int> jambone;

    jambone.push_back(2);
    jambone.front() = 4;
    std::cout<< jambone.front();
}

I'm not trying to do anything fancy here with multiple threads or anything. That should be fine, right? Would it be any different if it were a container full of objects, and I invoked a mutator on one of them?

1 Answers1

6

I think you are confusing 2 things about updating containers:

  1. std::set is not safe to update a value, as that will change the invariants (see what happens when you modify an element of an std::set?)

  2. With some containers—especially std::vector—you have to be careful if your operations (such as push_back) invalidate iterators and you are using iterators that you obtained before the operation.

With your situation, I do not see a problem with what your are doing.

Community
  • 1
  • 1
John Bandela
  • 2,416
  • 12
  • 19