Delaying drop because of borrow_mut

Today I encountered an interesting bug in my program. Given this piece of code:

let table: Rc<RefCell<HashMap<Object,Object>>> = some_table();

Now the return value of insert may be an object that calls drop and drop calls some arbitrary code which could then again take a borrow of table. And so it happened. At that time, however, table was still borrowed. The problem is averted easily by introducing a temporary variable to delay drop:

    let _delay = table.borrow_mut().insert(key,value);

My question now is, whether the behavior of the first version is intended, i.e. the order – dropping table before the RefMut value – is exactly specified.

It is how it always has been. The language is stable so will be consistent in order.

(note would be clearer to understand if written so referring to old_value.)

That kind of drop code sounds dangerous, but yes that is the intended order.

let _foo will definitely extend lifetime of the value until the end of the scope.

BTW, unlike named variables, let _ = is a special expression that drops immediately.

1 Like

Would the compiler in that let _ = ... case push the data to the stack and immediately pop it out?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.