问题描述
在我的C ++项目中,我有一个App类和一个Window类.类App的参数为:vector<Window*>* window;
.
In my C++ project, I have a class App, and a class Window. Class App has a parameter: vector<Window*>* window;
.
在App的构造函数中,它可以使用Window *并将其推回该矢量上,但是在我的onMessage()方法中,该方法由WndProc()调用(我正在使用winapi),它为我提供了当我尝试使用向量时发生运行时错误.这些是访问错误.
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.
推荐答案
指向向量的指针无效或向量中的指针无效;在这种情况下可能是前者.在许多情况下会发生这种情况,例如使用指向自此被销毁的本地对象的指针.
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.)
与其在App中存储矢量指针,不如存储矢量本身.不用存储指向Window对象的指针,而是自己存储Window对象.
Instead of storing a vector pointer in App, store a vector itself. Instead of storing pointers to Window objects, store the Window objects themself.
struct App {
vector<Window> windows;
};
但是,这要求Windows是可复制的,而它们可能不是.它还不允许存储从Window派生的类型的对象.相反,您可以使用 boost :: ptr_vector ,它拥有"指向的对象,并在删除它们(例如ptr_vector被销毁或清除)时将其删除:
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):
struct App {
boost::ptr_vector<Window> windows;
App() {
// just an example
windows.push_back(new Window());
windows.push_back(new DerivedFromWindow());
}
};
这篇关于存取向量时发生执行阶段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!