Misuse of GL info log null terminating character in std::string?

跟風遠走 提交于 2019-12-05 22:25:34

Yes, this is a valid use of std::string. You can get a pointer to the first character and write to the array of characters, so long as you don't exceed the range [0, size()).

However, you did make one mistake. See, GL_INFO_LOG_LENGTH includes the NUL terminator character in the length. Which means that, technically speaking, your std::string is one character longer than it needs to be. The last character of info will be a NUL character, and the std::string will treat that like it is part of the string's data, rather than a delimiter marking the end of the string.

You should not try to fix this by subtracting 1 from len before setting info's size. Why? Because glGetShaderInfoLog will always NUL terminate the string it writes. So if you shrink len, it will chop off the last actual character from the log.

Instead, you should shrink info after you've copied it from OpenGL:

info.resize(static_cast<std::string::size_type>(len));
glGetShaderInfoLog(gl_shader_obj, len, NULL, & info[0]);
info.pop_back();

In C++17, the standard wording has changed to allow writing to the NUL-terminator of a string, so long as you are overwriting it with a NUL character. It also allows string::data to return a non-const character array. Therefore, this will work fine now:

info.resize(static_cast<std::string::size_type>(len - 1));
glGetShaderInfoLog(gl_shader_obj, len, NULL, info.data());

The standard requires that info will have size+1 bytes in it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!