Humilton
Humilton

Reputation: 1063

C++ pointer/object error

I have this code, where I'm creating a SFML-Text object. But when I try to put this into a function I get an error. I have a programming background in Java, and this pointer-thing confuses me.

Is this a problem caused by incorrect use of pointers/reference, or because of object not surviving the scope? Or, is it something else?

void createDisplayText(sf::Text *text, string content, sf::Font font)
{
    text->setFont(font);
    text->setCharacterSize(24);
    text->setString("Money: 0");
}

//Main function
sf::Text energyText;
createDisplayText(&energyText, "Energy: ", font);
energyText.move(0, 30);


//Main loop
    window.draw(energyText);

I get this error:

Unhandled exception at 0x0F58FE8C (sfml-graphics-d-2.dll) in SFML_testing.exe: 0xC0000005: Access violation reading location 0x0000000C.

Upvotes: 0

Views: 61

Answers (2)

deviantfan
deviantfan

Reputation: 11434

The third parameter of createDisplayText, ie. font, is the (or "a") problem. If you call createDisplayText with some font there, it gets copied, the copy is used within the function, and deleted again when the function ends.

But in the function, you call text->setFont, which takes a reference: It won´t copy the parameter again, but uses your first copy directly. And as said before, this first copy gets deleted soon after. While this is no problem for text->setFont (because it has ended too if createDisplayText ends), it stores the font somewhere in the Text class for later use. And then...

(See the docs for setFont too: "The font argument refers to a font
that must exist as long as the text uses it.")

One solution of many: Pass the font of createDisplayText per reference too (sf::Font &font instead of sf::Font font) and take care that the font in main (etc.) will survive until it´s not needed anymore (it´s hard to say how without knowing the main function).

PS: In Java, everything behaves like a pointer. The non-pointer stuff should be the real confusing part...

Upvotes: 2

CyberGuy
CyberGuy

Reputation: 2813

It is almost impossible to find a bug in code above. The lucky guess is that your variable energyText goes out of the scope, when you are passing it to main loop.

Probably the best would be to run it with GDB and Valgrind.

Upvotes: 1

Related Questions