我有一个对象列表:
struct reply_t {
unsigned int xid;
char *buf;
};
std::list<reply_t> > replies;
我想删除该列表的一些元素(那些 xid <= confirmed_id
)。我喜欢 std :: remove_if
提供的简洁性.
remove_if(replies.begin(), replies.end(),
[&confirmed_id](const reply_t &arg) { return arg.xid <= confirmed_id; });
问题是这不会释放 buf
s(分配在其他地方)。有没有一种优雅的方法来处理这个问题?是不是在对象析构函数中加入free(buf)那么简单?
最佳答案
您可以为 reply_t 实现一个删除 buf 的析构函数:
struct reply_t {
unsigned int xid;
char *buf;
~reply_t() { delete buf; }
};
关于c++ - STL 容器中的内存释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36967885/