Reputation: 397
I have a function,
std::string ReadShader(const std::string& filePath) {
std::ifstream stream(filePath);
std::string line;
std::stringstream ss;
while (getline(stream, line)) {
ss << line << '\n';
}
return ss.str();
}
which works when I use these two lines of code,
std::string vertexShaderString = ReadShader("Shader/Vertex_Shader.vs");
const GLchar * vertexShaderSource = vertexShaderString.c_str();
i.e., vertexShaderString
contains the expected string, and vertexShaderSource
shows the first character of the expected string.
However, when I try a single line of code, viz.,
const GLchar * vertexShaderSource = (ReadShader("Shader/Vertex_Shader.vs")).c_str();
vertexShaderString
has a consistent line of characters with a hex code of 0xdd, and vertexShaderSource
shows the same 0xdd first character. That is, there is nothing of the expected string in either.
GLchar
is an OpenGL typedef for char
.
I think there is a C++ basic something I am missing.
Upvotes: 0
Views: 164
Reputation: 171293
Your second version of the code is similar to this:
const GLchar * vertexShaderSource;
{
std::string tmp = ReadShader("Shader/Vertex_Shader.vs");
vertexShaderSource = tmp.c_str();
} // tmp is destroyed here
I hope this makes it more obvious that your pointer is referring to the contents of a std::string
that has gone out of scope and deallocated its memory.
Upvotes: 4