C ++ - 无法更改向量<const glchar * =“”>中的特定向量

时间:2018-04-14 10:04:41

标签: c++ opengl vector

我在opengl中制作游戏,我在将字符串转换为const char *时遇到了问题。这是我的代码:

    for (GLuint i = 0; i < faces.size(); i++)
    {
        string      fileName(faces[i]),
                    texture = "../content/skybox/" + fileName + ".jpg";
                    faces[i] = texture.c_str();
    }
不幸的是,一旦运行,面孔[i]就变得一团糟。

2 个答案:

答案 0 :(得分:1)

您有未定义的行为:

Texture AssetController::LoadCubeMapTexture(vector<const GLchar*> faces, string ID)
{
    for (GLuint i = 0; i < faces.size(); i++)
    {
        string      fileName(faces[i]),
                    texture = "../content/skybox/" + fileName + ".jpg";

                    // !!!! texture is a local variable and will be
                    //      destroyed once its scope ends (which is 
                    //      on next for iteration, or when for ends).
                    faces[i] = texture.c_str();
    }

解决方案是将接口更改为返回文件名的向量:

Texture AssetController::LoadCubeMapTexture(vector<const GLchar*> faces, string ID, 
                               std::vector<std::string>& facesFileNames)
{
    for (GLuint i = 0; i < faces.size(); i++)
    {
        string      fileName(faces[i]);
        std::string texture = "../content/skybox/" + fileName + ".jpg";
        facesFileNames.emplace_back(texture);
    }

答案 1 :(得分:0)

一旦离开循环,std::string texture超出范围,就会调用析构函数,faces[i]指向的内存将变为无效。

只需使用std::vector<std::string>

在网站上注意:不要using namespace std