-
Notifications
You must be signed in to change notification settings - Fork 373
Description
Types like unique_ptr<int>
have nontrivial destructors, but nevertheless can be supported by value in Rust. They can be moved around in memory with memcpy, and we need only destroy the final object via Drop
.
C++ calls this property "trivially-relocatable" and it will finally be standardized in C++26.
While unique_ptr
has special support in cxx, many other types fall into this category, e.g. PIMPL classes. Today, cxx requires them to be Opaque and therefore boxed as e.g. UniquePtr
, adding a layer of indirection and an extra heap allocation. I would suggest a new cxx::kind::Relocatable
for these types:
#[cxx::bridge]
mod bridge {
extern "C++" {
type Database;
}
}
unsafe impl ExternType for Database {
type Id = type_id!("Database");
type Kind = cxx::kind::Relocatable;
}
cxx would generate impl Drop for Database
which calls the C++ destructor, and generate static_assert(std::is_trivially_relocatable<Database>)
. (As that type trait isn't available before C++26, cxx can define an alternative extension point similar to the somewhat-unfortunately-named cxx::IsRelocatable
)
An alternative would be to extend cxx::kind::Trivial
to allow types with destructors, but this would require impl Drop
for such trivial types, which adds overhead unless eliminated by e.g. LTO.
Would you be likely to accept a patch for this feature?