【发布时间】:2011-10-02 02:19:36
【问题描述】:
你能帮我弄清楚这段代码吗: onCreate(xMsg) 由 WindowProcedure 在 WM_NCCREATE 消息上调用。问题在于迭代器取消引用。我似乎无法将迭代器设置为列表的 begin(),然后获取迭代器的内容,它应该是指向可以与 MessageBox 中的 ->c_str() 一起使用的字符串的指针。
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);
}
【问题讨论】:
-
运行时错误?编译时错误?错误信息?
-
有什么理由不直接使用
std::string而是使用指针?std::string具有安全复制(现在是移动)语义,因此在容器中使用它比使用指向它的指针或char*更安全。 -
您的代码看起来不错。 “工作不正常”是什么意思???
-
运行时错误只是它有一个错误并决定通过微软检查它的解决方案我猜。至于将容器用于字符串,我只知道我以前遇到过这个问题并且无法弄清楚,而我只是一个解决这个问题的坚持者。
-
如果你在你的代码中分配
const char* striter = (*m_stringlistiter)->c_str();,你会得到“Hello world”吗?它似乎对我有用......