objc2 icon indicating copy to clipboard operation
objc2 copied to clipboard

Handling objects passed as "out parameters"

Open madsmtm opened this issue 1 year ago • 1 comments

See Passing to an out parameter by writeback.

Some methods take pointers to an instance, and, if the pointer is not NULL, write some value to the pointer. Examples include:

Note that out parameters work by autoreleasing the value - there may be a design where we embrace this, allowing us to cut down on some unnecessary retains and releases:

// Id<T, O> -> Id<T, O>
{
    let mut foo: Option<Id<T, O>>;
    // let old_foo = foo;
    msg_send![abc validateValue: &mut foo];
    // [old_foo release]
    // [foo retain]

    drop(foo)
}

// &T -> &T (easily possible today, but not very clear that the reference is bound to the pool)
pool {
    let mut foo: Option<&T>;
    msg_send![abc validateValue: &mut foo];

    // `foo` still usable inside the pool
}

// Id<T, O> -> &T
pool {
    let mut foo: Option<Id<T, O>>;
    // let old_foo = foo;
    msg_send![abc validateValue: &mut foo];
    // [old_foo release]
    let new_foo: &T = foo;
}

// &T -> Id<T, O>
pool {
    let mut foo: Option<&T>;
    msg_send![abc validateValue: &mut foo];
    // [foo retain]
    let new_foo: Id<T> = foo;
}

madsmtm avatar Oct 06 '22 01:10 madsmtm

One implementation is the current Id::writeback (name up for bikeshedding).

But I'm wondering whether we could just allow passing &mut Option<Id<T, O>>/Option<&mut Option<Id<T, O>> in msg_send!, and let it automatically handle the required retain/release?

madsmtm avatar Oct 06 '22 01:10 madsmtm

Also: Can we let it be automatically handled in declare_class!?

madsmtm avatar Oct 26 '22 16:10 madsmtm