访问向量时出现运行时错误
在我的 C++ 项目中,我有一个类 App 和一个类 Window。 App 类有一个参数:vector
。
在 App 的构造函数中,它可以很好地使用并将 Window* 推回到该向量上,但是在我的 onMessage() 方法中,该方法由 WndProc() (我使用的是 winapi)调用,它在以下情况下给我一个运行时错误:我尝试使用向量。这些是访问错误。
到底出了什么问题?如果您需要更多信息,请询问。
In my C++ project, I have a class App, and a class Window. Class App has a parameter: vector<Window*>* window;
.
In App's constructor, it is able to use and push_back a Window* onto this vector fine, but in my onMessage() method, which is called by the WndProc() (I'm using winapi), it gives me an runtime error when I try to use the vector. These are access errors.
What on earth could be going wrong? If you need any more info, just ask.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要么指向向量的指针无效,要么向量中的指针无效;在这种情况下可能是前者。这种情况在很多情况下都会发生,例如使用指向已被销毁的本地对象的指针。
(旁白:鉴于您为 window 添加了分号,我敢打赌这是一个数据成员而不是参数。)
不要在 App 中存储向量指针,而是存储向量本身。不存储指向 Window 对象的指针,而是存储 Window 对象本身。
然而,这要求 Windows 是可复制的,而它们可能不是。它还不允许存储从 Window 派生的类型的对象。相反,您可以使用 boost::ptr_vector,它“拥有”所指向的对象,并在它们被擦除时删除它们(例如当 ptr_vector 被销毁或清除时):
Either the pointer to the vector is invalid or the pointers in the vector are invalid; probably the former in this case. This happens in many situations, such as using pointers to local objects which have since been destroyed.
(Aside: Given that you included a semicolon for window, I bet this is a data member rather than a parameter.)
Instead of storing a vector pointer in App, store a vector itself. Instead of storing pointers to Window objects, store the Window objects themself.
However, this requires Windows to be Copyable, and they probably aren't. It also disallows storing objects of types derived from Window. Instead, you can use a boost::ptr_vector, which "owns" the pointed-to objects and will delete them when they are erased (such as when the ptr_vector is destroyed or cleared):