为什么此代码会导致访问冲突?

时间:2012-09-30 00:46:15

标签: c++ inheritance boost sdl

这个函数完全正常,或者编译器/调试器告诉我

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

1 个答案:

答案 0 :(得分:6)

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

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

您应该推送动态对象,该对象将存在components

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

请参阅doc: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
相关问题