Runtime error accessing a vector

六眼飞鱼酱① 提交于 2019-12-12 02:45:19

问题


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.


回答1:


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.

struct App {
  vector<Window> windows;
};

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());
  }
};


来源:https://stackoverflow.com/questions/3739905/runtime-error-accessing-a-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!