dtolnay / cxx

Safe interop between Rust and C++
https://cxx.rs
Apache License 2.0
5.85k stars 331 forks source link

Expose unique_ptr nullability more idiomatically in Rust #115

Open dtolnay opened 4 years ago

dtolnay commented 4 years ago

Currently cxx::UniquePtr<T> in Rust is equivalent to std::unique_ptr<T> in C++, which is sensible.

However, sometimes we know a particular UniquePtr is never supposed to be null:

mod ffi {
    extern "C++" {
        type C;
        fn create() -> UniquePtr<C>; // never supposed to be null
        fn with_ref(c: &C);
    }
}

This ends up being inconvenient from the Rust side because every call to with_ref is going to do a nullness check as part of turning &UniquePtr<C> into &C to pass as the argument.

Some possibilities that would maybe be better:

myronahn commented 4 years ago

Perhaps we could define a NonNullUniquePtr<T> which has a corresponding non_null_unique_ptr<T> in C++.

There would be a runtime check for NULL when you construct the non_null_unique_ptr<T> but there would be no check as the value moves across the FFI boundary, so it would basically push the runtime check into the C++ code (maybe where it belongs).