for(ItemTemplateListIterator iter = item_template_list.begin(); iter != item_template_list.end(); ++iter) {
int id = iter->first;
string de开发者_运维知识库scription = iter->second->description;
some_file_stream << id << endl;
some_file_stream << description << endl;
}
Where item_template_list is a map
of <int, MyClass*>
, ItemTemplateListIterator
is a typedef for a const_iterator
of map<int, MyClass*>
and MyClass
has a public string property called description.
What very likely happened is that the object pointers that you stored in the map are not valid anymore (because the memory was deallocated elsewhere). Attempting to access a deallocated memory area causes a segfault. Not valid is meaning either NULL
or having a so-called "dangling pointer".
Maybe also you are modifying the map or objects in the map in another thread while iterating through it.
There is too little code here for me to help you more.
I'll take a shot.
One of the MyClass* (pointers) has a "junk" (incorrect) value when you try to access it and boo-m. Segfault city.
As commented, you can store the full object in the map and not bother with pointers.
one of (iter->second) == null
The reason this is segfault is probably because the MyClass* is null or has been freed and has garbage value.
You can easily find out if it's null:
MyClass * obj = iter->second;
if (obj == null) {
cerr << "Unexpected null pointer" << endl;
} else {
string description = obj->description;
some_file_stream << id << endl;
some_file_stream << description << endl;
}
However, you still need to go through the rest of your code that populates the list and find out why it's not what you expected it to be.
Overall I'd say unless you're aiming to eliminate unnecessary copying of objects you'll be safer to store actual objects in the list and just make sure your copy constructor can handle them.
精彩评论