views:

86

answers:

1

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.

+2  A: 

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());
  }
};
Roger Pate
Turns out that I was accessing an object that didn't exist ( pointers... )
Alexander Rafferty