c++ - 为什么通过流获取的 std::string 被覆盖?

标签 c++ ifstream stdstring c-strings ostringstream

假设我有这样一个函数:

std::string get_shader(std::string path) {
     std::string fullpath = "./resources/shaders/" + path;
     std::ifstream vertexShaderFile(fullpath);
     std::ostringstream vertexBuffer;
     vertexBuffer << vertexShaderFile.rdbuf();
     return vertexBuffer.str();
}

然后是这样的代码:

GLuint vertex_shader;
GLuint fragment_shader;
GLuint program;

const GLchar * vertex_shader_source = get_shader("triangle_vertex.vs").c_str();

// At this point vertex_shader_source is correct.

const GLchar * fragment_shader_source = get_shader("fragment.vs").c_str();

// Now vertex_shader_source is the same as fragment_shader_source

我不明白为什么 vertex_shader_source 最终会被随后调用 get_shader 覆盖。我该如何解决这个问题?

最佳答案

const GLchar * vertex_shader_source = get_shader("triangle_vertex.vs").c_str();

vertex_shader_source 绑定(bind)到从 get_shader 返回的临时 std::string“内部”的值。这根本不会“延长”临时文件的生命周期。一旦该语句的执行完成并继续,该临时内存(以及您现在持有的指针)将无法再以定义的方式访问。

本质上你是在调用未定义的行为。

vertex_shader_source 更合适的声明可以是 std::string。由于该值是从函数返回的,因此它是一个右值,将调用适当的移动构造。

std::string vertex_shader_source = get_shader("triangle_vertex.vs");

如果此时您仍然是 const GLchar*vertex_shader_source.c_str() 就可以了。

关于c++ - 为什么通过流获取的 std::string 被覆盖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35425068/

相关文章:

c++ - 实现数据结构时使用智能指针还是原始指针?

python - 在 boost::odeint 中指定插值时间

c++ - 使用 constexpr、SFINAE 和/或 type_traits 对 char*、char 数组和字符串文字进行重载解析

c++ - 如何在特定索引处将64位 float 添加到无符号char数组(C++)

c++ - 无法从不区分大小写的字符串中提取 double ?

c++ - 如何将文件中的日期时间解析为 C++ 中的类

c++ - 读写同一个文件fstream

c++ - 使用 ifstream 读取文件

c++ - std::getline 没有产生正确的输出 (c++)

c++ - 除了使用 str.substr( ) 在给定位置提取子字符串之外,还有其他方法吗?