lig*_*rst 1 c++ stl dynamic-memory-allocation
我有一个列表定义为std::list<BunnyInfo> bList;私有,在类中BunnyInfo是一个结构
struct BunnyList::BunnyInfo {
std::string name;
char gender;
std::string color;
unsigned int age : 6; // 0 - 63
bool mutant;
};
Run Code Online (Sandbox Code Playgroud)
列表通过成员函数增长的位置
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);
}
}
Run Code Online (Sandbox Code Playgroud)
where fill()只是一个为结构生成值的函数.我还有一个删除列表一半的成员函数
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,如何删除列表成员,同时释放通过分配的资源add().delete &(*iter);我认为,产生错误,因为没有它,程序运行正常.但是简单地调用erase()不会释放BunnyInfo与列表节点关联的.
我是新手使用STL.
由于列表已声明std::list<BunnyInfo>,因此它insert会复制正在插入的对象,并erase自动处理该副本.因此,您不需要也不能delete在该副本上使用.
由于您add使用new的对象不分配delete(并且不存储在任何数据结构中),因此存在内存泄漏add.
如果要在列表中存储指针,则需要将列表声明为std::list<BunnyInfo *>.
| 归档时间: |
|
| 查看次数: |
389 次 |
| 最近记录: |