Reputation: 7176
I know that this "sometimes" is a little bit against the rules of stack overflow, but I don't know how to describe my problem in a better way:
I have this code:
static const std::string parseShader(const std::string &fileName){
std::ifstream ifs(fileName);
std::stringstream buffer;
buffer << ifs.rdbuf();
std::string s = buffer.str();
return s;
}
And in my main function I have this code:
const GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER);
const char* vertex_shader_text = parseShader("res/shaders/basic.vertex.glsl").c_str();
std::cout << "Vertex shader length is " << strlen(vertex_shader_text) << std::endl;
glShaderSource(vertex_shader, 1, &vertex_shader_text, NULL);
glCompileShader(vertex_shader);
const GLuint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
const char* fragment_shader_text = parseShader("res/shaders/basic.fragment.glsl").c_str();
std::cout << "Fragment shader length is " << strlen(fragment_shader_text) << std::endl;
glShaderSource(fragment_shader, 1, &fragment_shader_text, NULL);
glCompileShader(fragment_shader);
So, if I execute my program, without moving files or change any code, sometimes I get:
Vertex shader length is 160
Fragment shader length is 90
And sometimes:
Vertex shader length is 0
Fragment shader length is 0
And even, most of times
Vertex shader length is 160
Fragment shader length is 0
So, seems like some part of file reading would be asynchronous and slower than the rest of the program. I'm working with C++17, CLion and MacOS Mojave, as additional information....
Also, when both files are read correctly, then the image in opengl (a triangle) is correctly painted, but when some of the files are incorrectly read, nothing is shown.
Upvotes: 0
Views: 335
Reputation: 409136
The problem is that the string object that the function returns is temporary and will end its life-time almost immediately. That will leave you with a pointer to a string that no longer exists.
Use a std::string
as the destination instead, and only use the c_str
member function to get a pointer when absolutely needed.
Upvotes: 4