【问题标题】:Why does this code lead to an access violation?为什么此代码会导致访问冲突?
【发布时间】:2012-09-30 09:16:31
【问题描述】:

这个函数工作得很好,或者编译器/调试器告诉我

void GUIManager::init(ToScreen* tS)
{
    toScreen = tS;
    loadFonts();
    GUI_Surface = SDL_SetVideoMode( toScreen->width, toScreen->height, 32, SDL_SWSURFACE );
    components.push_back(&PlainText("Hello, World!", font, -20, -40));

}

在这里,第一个函数调用引发了访问冲突错误。 调试器没有显示任何问题。 我没有机会调试组件[0],因为程序在这里停止。

void GUIManager::draw() 
{
    // This line here is the problem
    components[0].draw(GUI_Surface);
    // This line here is the problem


    SDL_BlitSurface(GUI_Surface, NULL, toScreen->Screen_Surface, NULL);
}

如果需要,这是我的“组件”

boost::ptr_vector<GUIComponent> components;

如果需要任何其他代码,请告诉我。也许是 PlainText 或 GUIComponent

【问题讨论】:

  • 在drwaing之前检查components中的元素数量是否不为零。
  • 组件[0].position.x += 1;通过就好了。
  • 您正在将局部变量的地址推送到组件中。鉴于此内存已被释放,以后对它的任何访问都可能导致访问冲突。

标签: c++ inheritance boost sdl


【解决方案1】:

而不是将指针推送到临时的,它会在这一行之后结束其生命周期:

components.push_back(&PlainText("Hello, World!", font, -20, -40));

你应该推送动态对象,只要components就存在:

components.push_back(new PlainText("Hello, World!", font, -20, -40));

见文档:http://www.boost.org/doc/libs/1_51_0/libs/ptr_container/doc/ptr_sequence_adapter.html#modifiers

void push_back( T* x ); 
    Requirements: x != 0 
    Effects: Inserts the pointer into container and takes ownership of it
    Throws: bad_pointer if x == 0
    Exception safety: Strong guarantee

【讨论】:

  • 值得注意的是,boost::ptr_vector 稍后会管理对象的删除,这与 std::vector 不同。
  • @Dynguss true - 添加完整文档。
  • 非常感谢。成功解决了问题。另外,我肯定会查看该文档。
猜你喜欢
  • 1970-01-01
  • 2020-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-30
  • 1970-01-01
  • 1970-01-01
  • 2019-12-29
相关资源
最近更新 更多