如何返回null终止const char*的向量?

Tho*_* An 0 c++ pointers const

我试图逐行读取文件.将每一行转换为以空字符结尾的字符串.将所有行推入向量并返回.

vector<const char*> TypeGLscene::LoadGLshader (string ThisFile)
{
ifstream fromFile;
fromFile.open(ThisFile);
if (fromFile.good()==false)
{
    cout<<"Could not find file: "<<ThisFile<<endl;
    exit(1);
}

vector<const char*>  FileContents;
const char*    OneLine;
string         LineStr;

while (fromFile.good()==true)
{
    getline(fromFile,LineStr);
    OneLine = LineStr.c_str();
    FileContents.push_back(OneLine);
}

fromFile.close();
return FileContents;
Run Code Online (Sandbox Code Playgroud)

问题是所有char字符串都是在堆栈中创建的,函数返回char*的向量.

我试图通过以下方式在堆上分配内存:

OneLine = new char[LineStr.size()+1];
Run Code Online (Sandbox Code Playgroud)

但我被卡住了,因为一旦分配,我就无法复制任何内容; 内容是const.

我怎么能在const char*上使用new关键字并在它实现它是const之前同时向它添加内容?

(更不用说我必须一个一个地删除它们,另一方面......真是一团糟)

编辑:我宁愿返回一个向量,但这一切都是因为我不知道快速(一行)方式将向量转换为const char**:

void glShaderSource(GLuint shader,
                    GLsizei count,
                    const GLchar **string,
                    const GLint *length);
Run Code Online (Sandbox Code Playgroud)

R S*_*ahu 5

回归std::vector<char*>是充满了问题.

  1. 你必须为每一行分配内存.该函数的客户端必须添加代码以释放内存.客户端代码变得比它需要的更复杂.

  2. 客户端函数必须知道是否char*使用malloc或分配operator new.他们必须根据用于分配内存的方法遵循适当的内存释放方法.客户再一次知道该功能的作用以及它是如何做到的.

一个更好的方法是返回一个std::vector<std::string>.

std::vector<std::string>  FileContents;
std::string LineStr;

while (fromFile.good()==true)
{
    getline(fromFile,LineStr);
    FileContents.push_back(LineStr);
}

fromFile.close();
return FileContents;
Run Code Online (Sandbox Code Playgroud)

如果您必须退货std::vector<char*>,您可以使用:

std::vector<char*>  FileContents;
std::string LineStr;

while (fromFile.good()==true)
{
    getline(fromFile,LineStr);
    char* line = new char[LineStr.size()+1];
    strcpy(line, LineStr.c_str());
    FileContents.push_back(line);
}

fromFile.close();
return FileContents;
Run Code Online (Sandbox Code Playgroud)