-5

vector pop_back, erase and clear do not destroy the elements of the vector:

vector <string> strs;
string text = "sample text";
strs.push_back(text);

strs.pop_back();
// or strs.clear();
// or erase(strs.begin());
cout << "vector size: " << strs.size() << "\n";  // returns "0" 
cout << strs[0]; // still returns "sample text", no error !
getc(stdin);

how comes the element isn't invalidated?

braX
  • 11,506
  • 5
  • 20
  • 33
  • 2
    A) it wouldn't compile. B) It is *undefined behaviour* to access vector elements out of range. – juanchopanza May 11 '14 at 10:58
  • 2
    Your code has a bug in it. Fix the bug and the mystery will go away. Your question is a classic example of "My code has a bug in it. Why doesn't it work as I expect it to?" and the answer is always "That's why we fix bugs." – David Schwartz May 11 '14 at 10:59
  • `strs.pop_back;` should be `strs.pop_back();`. – interjay May 11 '14 at 11:00

1 Answers1

1

The element was invalidated. The proof is that you got a result you were unable to predict. If it was valid, you would have been able to accurately predict the result. Because the element was invalidated, the result was entirely unpredictable so, unsurprisingly, you couldn't predict what would happen.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278