简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM