【发布时间】:2026-02-21 14:25:02
【问题描述】:
我有一个简单的 c++ 电话簿项目,我不能使用 std::vector。 所以我决定为自己创造一个。 我想请教一下我的 push_back 函数。
所以这是在vector.h中:
class Vector{
int siz; //size
std::string* elem; //elements
public:
Vector(): siz(0){}
int getSize()const;
void pushBack(std::string const&);
std::string operator[](int) const;
Vector& operator=(const Vector&);
};
这是我的 push_back 函数:
void Vector::pushBack(std::string const& s){
std::string* temp = new std::string[siz + 1];
for(int i = 0; i < siz; i++)
temp[i] = elem[i];
temp[siz] = s;
// delete[] elem; // The debugger points here
this->elem = temp;
this->siz += 1;
}
这是我使用 push_back 函数的地方:
const Vector read(){
Vector v;
std::ifstream file;
file.open("data.txt", std::ios::in);
int db = 10 * linecounter();
std::string temp;
for(int i = 0; i < db; i++)
{
if(i % 10 == 9 && i != 0){
getline(file, temp); // the last data in the line after that ther is a \n
v.pushBack(temp);
}
else{
getline(file, temp, ';'); // read in the temp till the ;
v.pushBack(temp); // The debugger points here
}
}
return v;
}
我的问题是,当我不使用delete[] elem; 时,它会造成一些内存泄漏。当我使用时,程序立即崩溃。
【问题讨论】:
-
您没有在构造函数中将 elem 初始化为 nullptr
-
@KillzoneKid
temp[i] = elem[i]不会在第一次 pushBack 中执行,因为那时siz将是0。 -
@t.niese 对!