将任意对象附加到数组有什么问题



我有一个简单的程序,可以将文件中的字符串处理为任意类Student(下面提供(,并将其附加到自写容器ArraySequence中。当错误几乎总是发生在标记线上时(用*****标记(。

班级学生:

class Student {
public:
int year;
std::string name;
std::string surname;
Student(int _year, std::string _name, std::string _surname) {
this->year = _year;
this->name = _name;
this->surname = _surname;
}
Student(const Student& s) {
this->year = s.year;
this->name = s.name;
this->surname = s.surname;
}
Student& operator=(const Student& s) {
this->year = s.year;
this->name = s.name;
this->surname = s.surname;
return *this;
}
bool operator==(const Student& s) const {
if (this->year == s.year && this->name == s.name && this->surname == s.surname)
return true;
return false;
}
};

main:

int main() {
std::ifstream data("filename");
std::string buffer;
ArraySequence<Student>* entities = new ArraySequence<Student>;
getline(data, buffer, 'n');
while (buffer.size() != 0) {
std::cout << buffer << std::endl;
int len = static_cast<int>(buffer.find(" "));
std::string surname = buffer.substr(0, len);
buffer = buffer.substr(len + 1);
len = static_cast<int>(buffer.find(" "));
std::string name = buffer.substr(0, len);
int year = std::stoi(buffer.substr(len + 1));
Student b(year, name, surname);
entities->append(b); *****
getline(data, buffer, 'n');
}
std::cout << count << std::endl;

附加:

template <typename T>
void ArraySequence<T>::append(const T& item) {
ISequence<T>::length++;
if (!(ISequence<T>::length - 1)) {
data = (T*)malloc(sizeof(T));
}
else {
data = (T*)realloc(data, sizeof(T) * ISequence<T>::length);
}
*(data + ISequence<T>::length - 1) = item;
}

错误:Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT)Thread 1: EXC_BAD_ACCESS (code=1, address=0x3)

有时它只是工作,但有时它会因错误而崩溃。

我使用的是Xcode 11.1

在线程1中,它指出了c++ this->surname = s.surname;线上Student的运算符=的问题

在这种情况下我该怎么办?有什么想法吗?

T由一个非平凡类型组成(Student包含std::string,加上非平凡复制/赋值和析构函数(,使用mallocrealloc将无法正常工作。

CCD_ 9和CCD_。它们只分配内存。您的程序可能由于这些无效的Student对象而崩溃。

最简单的解决方案是将ArraySequence<T>::append重写为仅使用new[]delete[],而不使用mallocrealloc

注意:使用placement new时可以使用malloc,但您没有为此目的使用malloc

最新更新