[英]Returning a std::string, converting to char*
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();
ie, vertexShaderString
contains the expected string, and vertexShaderSource
shows the first character of the expected string. 即, vertexShaderString
包含期望的字符串,而vertexShaderSource
显示期望的字符串的第一个字符。
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. vertexShaderString
具有一致的字符行,十六进制代码为0xdd,并且vertexShaderSource
显示相同的0xdd第一个字符。 That is, there is nothing of the expected string in either. 也就是说,在任何一个中都没有期望的字符串。
GLchar
is an OpenGL typedef for char
. GLchar
是char
的OpenGL typedef。
I think there is a C++ basic something I am missing. 我认为我缺少C ++基本的东西。
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. 我希望这可以使您的指针更清楚地指向已超出范围并释放其内存的std::string
的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.