为什么通过流获得的std :: string被覆盖? [英] Why is my std::string obtained via stream being overwritten?

查看:149
本文介绍了为什么通过流获得的std :: string被覆盖?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个像这样的函数:

Assume I have a function like so:

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 的调用所掩盖。我该如何解决?

I don't understand why vertex_shader_source ends up being overwitten by a subsequent call to get_shader. How do I fix this?

推荐答案

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

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

The vertex_shader_source is bound to a value "inside" the temporary std::string returned from get_shader. This does not "extend" the lifetime of the temporary at all. Once the execution of that statement is complete and continues, that temporary, and it's memory (and the pointer you now hold) is no longer accessible in a defined manner.

基本上您正在调用未定义的行为。

Essentially you are invoking undefined behaviour.

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

A more appropriate declaration of the vertex_shader_source could be as a std::string. Since the value is being returned from the function, it is a rvalue and the appropriate move construction will be invoked.

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

如果您仍然使用 const GLchar * 此时, vertex_shader_source.c_str()即可。

If you still the the const GLchar* at this point, vertex_shader_source.c_str() will do.

这篇关于为什么通过流获得的std :: string被覆盖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆