My list of pointers to std::string objects is not working right, and I can't figure out why
Can you help me figure out this code: onCreate(xMsg) is called by the WindowProcedure on a WM_NCCREATE message. The problem is within the iterator dereferencing. I can't seem to set the i开发者_StackOverflowterator to the list's begin() and then get the contents of the iterator, which should be a pointer to a string which could be used with ->c_str() in a MessageBox.
class MyController
{
public:
MyController() { }
~MyController() { }
void onCreate(xMessage *msg);
protected:
std::list<std::string *> m_stringlist;
std::list<std::string *>::iterator m_stringlistiter;
};
void onCreate(xMessage *msg)
{
std::string *first_string = new std::string("Hello world");
m_stringlist.push_back(first_string);
// This is where my iterator comes into play and it doesn't seem to do the trick.
m_stringlistiter = m_stringlist.begin();
MessageBox(NULL, (*m_stringlistiter)->c_str(), "Title", MB_OK);
}
We aren't given the full example, but I assume that you are doing other manipulations in between the creation and use of the iterator.
Iterators are not guaranteed to be valid after varied operations on the container. You should not save them.
I'm willing to bet that this will work?
class MyController
{
public:
MyController() : title("Hello World") {}
void onCreate(xMessage *msg);
{
MessageBox(NULL, title.c_str(), "Title", MB_OK);
}
protected:
std::string title; // generic lists of strings with
// magic indexes are hard to maintain.
};
This is easier to read and debug too, which costs a lot more than any other part of software development.
You should use iterators as temporary objects, for the most part. Rarely do they extend outside of a function/method's scope.
struct some_struct {
some_struct() {
gui_text.push_back( std::string("Hello World!") );
}
void some_function() {
std::list<std::string>::iterator iter = gui_text.begin();
for (; iter != gui_text.end(); iter++) {
std::cout << *iter << std::endl;
}
}
std::list<std::string> gui_text;
};
Things like adding, deleting, etc from the container will invalidate iterators. So just recreate the iterator at each point. Strings and iterators are pretty lightweight, so you don't need to worry about optimizing in this way. Really.
精彩评论