[rust-dev] Drop and lifetimes

Steven Fackler sfackler at gmail.com
Tue Jul 1 09:22:31 PDT 2014

Drop implementations for types with lifetime parameters need to be tagged
with #[unsafe_destructor] because they're currently unsound in certain
situations: https://github.com/rust-lang/rust/issues/8861. The intended
semantics are what you would expect: Cursor would drop before Database.
It's something that will be fixed before 1.0. Rust-Postgres uses this kind
of lifetime setup and it works pretty well (ignoring the memory corruption
which is hackily checked for right now with a canary):

You can't safely create a Thing. Cursor contains a pointer to the Database,
but the Database will move to a new location in memory when you place it
into the Thing, and every time Thing moves afterwards. All of those moves
will cause the Cursor's reference to the Database to point to stale memory.
You may be able to adjust Thing so it contains a reference to the Database

Steven Fackler

On Tue, Jul 1, 2014 at 7:35 AM, David Brown <davidb at davidb.org> wrote:

> Imagine a hypothetical database interface:
>    struct Database { ... }
>    struct Cursor<'a> {
>        db: &'a Database,
>        ...
>    }
>        impl Database {
>        fn query<'a>(&'a self, ...) -> Cursor<'a> { ... }
>    }
> Ideally, I would like both the Database, and the Cursor to implement
> Drop.  The underlying database API requires the cursors to all be
> closed before the database itself is closed.
> My first concern is that the trend seems to be to disallow Drop on the
> Cursor (it requires #[unsafe_destructor] to compile right now).
> My second concern is around what seems to be to be a reasonable use of
> this:
>    struct Thing<'a> {
>        db: Database,
>         q1: Cursor<'a>,
>         ...
>    }
> This would be common with the use of an SQL database, where there are
> a handful of prepared statements that get reused with different data.
> (minor other question, I can't figure out how to make a 'Thing',
> everything I've tried results in some kind of lifetime error).
> But, the question then becomes, what order would Drop be called when
> Thing goes out of scope?
> Am I missing a better way of doing all of this?  I don't see 'Rc' or
> 'Gc' helping, least because they only handle an immutable value, but
> also, they are non-Send, so can't have Drop either.
> Thanks,
> David Brown
> _______________________________________________
> Rust-dev mailing list
> Rust-dev at mozilla.org
> https://mail.mozilla.org/listinfo/rust-dev
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/rust-dev/attachments/20140701/56c9d622/attachment.html>

More information about the Rust-dev mailing list