我试图在以下函数中返回一个浮点数组:
static GLfloat *LoadFile(const char *filePath) {
std::ifstream f;
f.open(filePath, std::ios::in | std::ios::binary);
if(!f.is_open()){
throw std::runtime_error(std::string("Failed to open file: ") + filePath);
}
std::stringstream buffer;
buffer << f.rdbuf();
std::string s = buffer.str();
std::string delimiter = ",";
size_t pos = 0;
std::string token;
pos = s.find(delimiter);
token = s.substr(0, pos);
int numberOfItems = ::atof(token.c_str());
s.erase(0, pos + delimiter.length());
pos = s.find(delimiter);
token = s.substr(0, pos);
int componentsPerItem = ::atof(token.c_str());
s.erase(0, pos + delimiter.length());
int dataLength = numberOfItems * componentsPerItem;
GLfloat *data = new GLfloat[dataLength + 2];
data[0] = numberOfItems;
data[1] = componentsPerItem;
int counter = 2;
while ((pos = s.find(delimiter)) != std::string::npos) {
token = s.substr(0, pos);
GLfloat num = ::atof(token.c_str());
if (counter > dataLength + 1)
throw std::runtime_error(std::string("Error in vertex data file: ") + filePath);
data[counter] = num;
s.erase(0, pos + delimiter.length());
counter++;
}
return data;
}
但是当我设置一个等于返回值的变量时:
GLfloat *data = LoadData();
数据等于 NULL。我的印象是,因为我使用了 new 运算符,所以即使在我离开函数范围后,值也会保留。我究竟做错了什么?