为什么我的 std::字符串通过流获得被覆盖
Why is my std::string obtained via stream being overwritten?
假设我有一个这样的函数:
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
绑定到从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()
就可以了。
对于语句,
const GLchar * vertex_shader_source = get_shader("triangle_vertex.vs").c_str();
// The temporary `std::string` will be destroyed here.
get_shader
返回一个临时std::string
,该将在语句后销毁,这意味着vertex_shader_source
将持有无效指针,取消引用将导致 UB。
您所看到的可能是由解除分配后的内存重用引起的,但 UB 是 UB,一切皆有可能。
您可以为其定义一个命名变量,例如:
std::string vertex_shader_source_string = get_shader("triangle_vertex.vs");
const GLchar * vertex_shader_source = vertex_shader_source_string.c_str();
相关文章:
- 为什么我的全局 new() 覆盖被绕过了?
- 为什么我的二叉树会覆盖其根的叶子?
- 为什么我的类节点覆盖自身而不是创建新的节点对象
- 当读取错误类型时,CIN覆盖我的初始化值
- 为什么我的程序一直给我堆缓冲区溢出,即使我没有超出数组的界限或覆盖任何值
- 在我的代码覆盖本身时遇到麻烦,我不确定为什么
- c ++ 我的 char* 数组被最后一个添加的元素覆盖
- 为什么没有调用我的覆盖方法
- 为什么我不能简单地覆盖<对的优先级队列?
- C++ 为什么我的覆盖代码 const int x = *(&y);工作?
- 覆盖我正在扩展的嵌套类的方法
- C++中的第一个覆盖前缀-我的代码出了什么问题
- 为什么Visual C++中的“我的语言”翻译器程序不用翻译就覆盖文件
- 为什么我的列表值被覆盖
- 为什么我的 std::字符串通过流获得被覆盖
- 如何覆盖我当前正在运行的可执行文件
- 我认为python正在覆盖我的vtable(c ++扩展)
- 为什么在交叉编译时不 cmake CMAKE_FIND_ROOT_PATH 和 CMAKE_INCLUDE_PATH 覆盖我的根文件系统?
- 我是否需要使用继承对象(相对于基对象)覆盖我的虚函数?
- 相同的函数名称与不同数量的参数覆盖我的基本函数