【发布时间】:2014-05-26 00:21:12
【问题描述】:
我想知道是否有办法在值从堆中释放之前返回它。
我的问题是,如果我这样做:
queue_item *dequeue(queue *this) {
node old = this->front;
this->front = old->link;
free(old->item);
free(old);
return(old->item);
}
显然是旧的->项目在返回之前从堆中取出。目前为了解决这个问题,我存储了以前在字段中使用的项目。然后我在下次出队时释放该项目。最后,我杀死了队列析构函数中的最后一项。
queue_item prev_item;
queue_item *dequeue(queue *this) {
assert (!queue_isempty (this));
node old = this->front;
this->front = old->link;
queue_item item = old->item;
free(prev_item);
prev_item = old->item;
free(old);
return(old->item);
}
void queue_destruct(queue this) {
free(prev_item);
free(this)
}
但我对这种方法不太满意,因为我总是在堆上多了一个项目。有没有解决的办法?我是否缺少某种优雅的解决方案?
【问题讨论】:
-
如果需要返回值不应该是
freed