Hi,
Why is the following code does not work; "delete(s)" causes segmentation
fault. But if I change the program to use "map
Please ignore the question. I just found out the answer. Apparently STL containers perform defensive copy on every argument and return value. -- -- Verdi March --
Verdi March wrote:
Hi,
Why is the following code does not work; "delete(s)" causes segmentation fault. But if I change the program to use "map
m", "delete(s)" will sucessfully run. int main() { map
m; string *s = new string("first"); m[*s] = string("first value");
s = new string("second");
/* Oops. You've just thrown away the only pointer to the previous * value of s */
m[*s] = string("second value");
map
::iterator it = m.begin(); for (int i = m.size(); i > 0; i--, it++) { const string* s = &(it->first); delete(s); //this causes segmentation fault.
/* If you want to delete the entry in map corresponding to * it, use m.erase( it ). This attempts to delete something * you didn't create with new - usually a bad idea. */
}
return 0; }
The whole thing can be done more easily as
int main() {
map
participants (2)
-
John Lamb
-
Verdi March