根据valgrind的说法,我的代码中存在内存泄漏,它们全部来自类的构造函数;这是它的代码:
School::School(unsigned int NumberOfClasses[]) :
first(*new Grade<Student, std::equal_to<Student>>(NumberOfClasses[0])),
second(*new Grade<Student, std::equal_to<Student>>(NumberOfClasses[1])),
third(*new Grade<Student, std::equal_to<Student>>(NumberOfClasses[2])) {
}
Grade是我创建的特殊数组模板,它同时获取一个元素(在本例中为Student)和该元素的比较函数(我也提供了);它既有构造函数,也有析构函数,可以在没有内存泄漏的情况下工作。这是构造函数的标题:
Grade<Element, Compare> :: Grade(unsigned int size);
因为我的学校是3年级,所以其析构函数是= default;
这是我从valgrind得到的:
8 bytes in 1 blocks are indirectly lost in loss record 1 of 6
==21426== at 0x4C2A888: operator new[](unsigned long) (vg_replace_malloc.c:423)
==21426== by 0x4041B8: Grade<BmbSchool::Student, std::equal_to<BmbSchool::Student> >::Grade(unsigned int) (GradeImp.h:9)
==21426== by 0x40298B: BmbSchool::School::Grade(unsigned int*) (School.cpp:27)
==21426== by 0x405B6C: main (BmbSchool.cpp:148)
类似的,我得到的另一种错误是:
==21426== 32 (24 direct, 8 indirect) bytes in 1 blocks are definitely lost in loss record 3 of 6
==21426== at 0x4C2A1E3: operator new(unsigned long) (vg_replace_malloc.c:334)
==21426== by 0x402974: BmbSchool::School::Grade(unsigned int*) (School.cpp:28)
==21426== by 0x405B6C: main (BmbSchool.cpp:148)
有任何意义吗?我该如何解决?我可以假设定义数组时不会抛出bad_alloc异常。
编辑:学校的定义是-
Grade<Student, std::equal_to<Student>> first;
Grade<Student, std::equal_to<Student>> second;
Grade<Student, std::equal_to<Student>> third;
谢谢!
泄漏是由于您滥用new
。您正在动态分配3个Grade
对象,但是随后取消引用指针来复制构造3个数据成员。您永远不会delete
您已new
编辑过的对象。
在这种情况下,您根本不需要new
,因此请摆脱它。只需将所需的值直接传递给数据成员构造函数:
School::School(unsigned int NumberOfClasses[]) :
first(NumberOfClasses[0]),
second(NumberOfClasses[1]),
third(NumberOfClasses[2])
{
}