因此,我有一个函数返回一个std::string,如下所示:
string ReadShaderSource(const char* filename, GLint& shaderSize) // Load the shader source code.
{
ifstream::pos_type size;
string text;
ifstream file(filename, ios::in | ios::binary | ios::ate);
if (file.is_open())
{
size = file.tellg();
shaderSize = (GLuint)size;
text.resize(size);
file.seekg(0, ios::beg);
file.read(&text[0], text.size());
file.close();
return text;
}
else
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Fatal Error!",
"Could not load the shader source code from the file.", NULL);
Lunar::Exit();
}
return "";
}但是当我像这样调用这个函数时:
const char* testStr = ReadShaderSource("test.glsl", size).c_str();testStr的值充满了以下内容:
0x036fdcd8 "îþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþ...
这毫无意义。函数返回正确的值,因此当我在函数中返回文本时,它包含着色器的源代码,但当我返回时。
const char* testStr = ReadShaderSource("test.glsl", size).c_str();testStr满是垃圾。
有什么想法吗?
谢谢!
发布于 2014-05-08 21:49:07
你需要用
string str = ReadShaderSource("test.glsl", size);
const char* testStr = str.c_str();而不是
const char* testStr = ReadShaderSource("test.glsl", size).c_str();使用第二种形式时,您将在testStr中存储一个指针,该指针不再有效,因为该函数的返回值是一个临时string。
正如@IInspectable所指出的那样,您还可以使用const&来延长临时对象的生存期。
string const& str = ReadShaderSource("test.glsl", size);
const char* testStr = str.c_str();以下程序表现良好:
#include <iostream>
#include <string>
std::string foo()
{
return "This is a test.";
}
void bar(std::string const& str)
{
std::cout << str.c_str() << std::endl;
}
int main()
{
std::string const& str = foo();
bar(str);
std::cout << str.c_str() << std::endl;
}发布于 2014-05-08 21:39:29
回复
“当我这么做的时候,
const char* testStr = ReadShaderSource("test.glsl", size).c_str();testStr满是垃圾。”
您正在初始化指针,以指向临时string中的缓冲区,该缓冲区在初始化结束时已经不复存在。
相反,对结果变量使用string。
请注意,函数返回垃圾的结论是没有道理的,它不是从垃圾的观察中得出的,但可能仍然是正确的。
您应该用适当的结果变量类型重新测试以检查这一点。
https://stackoverflow.com/questions/23552961
复制相似问题