正在释放std::list成员
freeing std::list member
在BunnyInfo
是结构的类中,我有一个定义为std::list<BunnyInfo> bList;
、private的列表
struct BunnyList::BunnyInfo {
std::string name;
char gender;
std::string color;
unsigned int age : 6; // 0 - 63
bool mutant;
};
其中列表通过成员函数增长
void BunnyList::add(int count){
bListIter iter;
while(count--){
BunnyInfo *bNew = &fill(*new BunnyInfo());
for(iter = bList.begin(); iter != bList.end(); iter++){
if(iter->age <= bNew->age)
break;
}
bList.insert(iter, *bNew);
}
}
其中CCD_ 3只是为结构生成值的函数。我还有一个成员功能,可以删除列表的一半
void BunnyList::reap(){
int toKill = bList.size() / 2;
int find;
bListIter iter;
while(toKill--){
find = rng(0, bList.size()-1);
iter = bList.begin();
for(int i = 0; i < find; i++) // traverse list to the find-th node;
iter++;
delete &(*iter);
bList.erase(iter);
}
}
我的问题是,如何删除列表成员,同时释放通过add()
分配的资源。我认为delete &(*iter);
会产生一个错误,因为没有它程序运行正常。但是简单地调用erase()
并不能释放与列表节点相关联的BunnyInfo
。
我是STL的新手。
由于列表被声明为std::list<BunnyInfo>
,它的insert
会复制插入的对象,而erase
会自动处理该副本。因此,您不需要也不能在该副本上使用delete
。
由于add
用new
分配了一个它不是delete
(并且不存储在任何数据结构中)的对象,因此add
中存在内存泄漏。
如果要在列表中存储指针,则需要将列表声明为std::list<BunnyInfo *>
。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 助记符和指向成员语法的指针
- 用于访问容器<T>数据成员的正确 API
- 内置函数可查看CPP中的成员变量
- C++ - 使用 std::list,如何打印对象的私有成员的链接列表?
- 关于使用 Std::List 作为类成员变量的奇怪错误
- 为什么 List 类必须包含 Node 结构作为私有成员C++
- C++ - 错误:'list'没有命名类型(将对象列为类中的成员变量)
- C++ std::list<T>::迭代器 迭代器是否具有<T>对成员函数的访问?
- C++:自定义'List'成员函数
- 模板类和继承问题 - 'List'不命名非静态数据成员或基类
- 正在释放std::list成员
- 以vector、list或map为成员的类需要复制构造函数
- 当需要成员数据时,如何对std:list进行排序
- std::list 的擦除成员函数是否为所有存储的元素调用析构函数?