Why does this code lead to access violation?

This function works fine, or so the compiler / debugger tells me

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

Here, the first function call causes an access violation error. The debugger does not show any problems. I do not get the opportunity to debug components [0], because the program stops here.

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

If necessary, these are my "components"

 boost::ptr_vector<GUIComponent> components; 

Just let me know if any other code is needed. Possibly from PlainText or GUIComponent

+4
source share
1 answer

Instead of clicking on a temporary pointer that ends its lifetime immediately after this line:

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

You must click on the dynamic object that will exist until components :

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

See 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 
+6
source

Source: https://habr.com/ru/post/1436998/


All Articles