访问向量时出现运行时错误

发布于 2024-09-24 06:39:50 字数 269 浏览 10 评论 0原文

在我的 C++ 项目中,我有一个类 App 和一个类 Window。 App 类有一个参数:vector* window;

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梅窗月明清似水 2024-10-01 06:39:50

要么指向向量的指针无效,要么向量中的指针无效;在这种情况下可能是前者。这种情况在很多情况下都会发生,例如使用指向已被销毁的本地对象的指针。

(旁白:鉴于您为 window 添加了分号,我敢打赌这是一个数据成员而不是参数。)

不要在 App 中存储向量指针,而是存储向量本身。不存储指向 Window 对象的指针,而是存储 Window 对象本身。

struct App {
  vector<Window> windows;
};

然而,这要求 Windows 是可复制的,而它们可能不是。它还不允许存储从 Window 派生的类型的对象。相反,您可以使用 boost::ptr_vector,它“拥有”所指向的对象,并在它们被擦除时删除它们(例如当 ptr_vector 被销毁或清除时):

struct App {
  boost::ptr_vector<Window> windows;

  App() {
    // just an example
    windows.push_back(new Window());
    windows.push_back(new DerivedFromWindow());
  }
};

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());
  }
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文