Confuse on str().c_str() and just c_str()

I was experimenting on reading file.

Then I found something kinda confusing. Why is it that if I pass a converted string stream
1
2
sample = VShaderStream.str().c_str();
cout << sample << endl;

to a Pointer to GLChar I got a weird result.

http://s23.postimg.org/icjea6fdn/Untitled.png



But if first I pass the stringstream to a string and then convert that string to c_str() and pass it to a Pointer to GlChar. I got the expected result

1
2
3
4
string  vertexCode = VShaderStream.str();
GLChar* vShaderCode = vertexCode.c_str();

cout << vShaderCode << endl;


http://s13.postimg.org/mzrnvma3r/Untitled2.png

Also even if I just do
cout << VShaderStream.str().c_str() << endl;

it will give the expected result.

I just dont understand the first one.






Last edited on
Simple: The first example creates a temporary std::string, and you take its internal data pointer, which points to invalid data as soon as the temporary is destroyed (after the semicolon).
In the second example, you create an explicit std::string, and you take its internal data pointer, which points to valid data as long as your std::string doesn't change.

In the last example, you also create a temporary std::string, and you take its internal data pointer, which was still pointing to valid data since it hasn't been destroyed yet (No semicolon between cout and VShaderStream.str().c_str().
Last edited on
VShaderStream.str() returns a temporary string and hence a pointer to a temporary c-string. As soon as clause ends (line1) the temporary string becomes invalid and so is the pointer. So on line 2 you will have garbage.

Also even if I just do
It's the same: When cout processes the pointer at the end of the stream clause the pointer is invalid.
Thanks, You guys are awesome
Topic archived. No new replies allowed.