Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: sf::String and std::string::c_str in SFML2  (Read 6439 times)

0 Members and 1 Guest are viewing this topic.

Groogy

  • Hero Member
  • *****
  • Posts: 1469
    • MSN Messenger - groogy@groogy.se
    • View Profile
    • http://www.groogy.se
    • Email
sf::String and std::string::c_str in SFML2
« on: December 12, 2010, 03:45:24 am »
Just wondering, is this intended behavior? I had this code:

Code: [Select]
const char * cString = string.ToAnsiString().c_str();
FILE * file = fopen(cString, "rb");

Opening the file would fail and when I debugged and looked at cString it would contain junk data. But if I skip the middle hand cString pointer and only write:
Code: [Select]

FILE * file = fopen(string.ToAnsiString().c_str(), "rb");

the file is actually opened and apparently it contains the proper characters.

Is this how it is intended to be designed or is std::string messing with me?
Developer and Maker of rbSFML and Programmer at Paradox Development Studio

Silvah

  • Guest
sf::String and std::string::c_str in SFML2
« Reply #1 on: December 12, 2010, 11:25:24 am »
It is how the language works. The temporary std::string created by a call to the ToAnsiString method lasts "to the semicolon", that is, it is destroyed at the end of the statement that created it.

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32498
    • View Profile
    • SFML's website
    • Email
sf::String and std::string::c_str in SFML2
« Reply #2 on: December 12, 2010, 12:07:35 pm »
You must store the returned std::string, not a pointer to its content. Otherwise, like Silvah explaines, the std::string is destroyed and the pointer points to invalid data.
Code: [Select]
std::string cString = string.ToAnsiString();
FILE * file = fopen(cString.c_str(), "rb");
Laurent Gomila - SFML developer

Groogy

  • Hero Member
  • *****
  • Posts: 1469
    • MSN Messenger - groogy@groogy.se
    • View Profile
    • http://www.groogy.se
    • Email
sf::String and std::string::c_str in SFML2
« Reply #3 on: December 12, 2010, 03:04:08 pm »
Aight then it's intended behavior :P

Anyway I was just checking in so it wasn't a unkown bug.
Developer and Maker of rbSFML and Programmer at Paradox Development Studio

 

anything