Skip to content

Commit fafa489

Browse files
author
Nicholas Matsakis
committed
clarify that Box<T> should only be used when defined *in Rust*
1 parent cb1cc11 commit fafa489

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed

src/liballoc/boxed.rs

+16-7
Original file line numberDiff line numberDiff line change
@@ -63,13 +63,14 @@
6363
//! T` obtained from `Box::<T>::into_raw` may be deallocated using the
6464
//! [`Global`] allocator with `Layout::for_value(&*value)`.
6565
//!
66-
//! So long as `T: Sized`, a `Box<T>` is guaranteed to be represented as a
67-
//! single pointer and is also ABI-compatible with C pointers (i.e. the C type
68-
//! `T*`). This means that you can have Rust code which passes ownership of a
69-
//! `Box<T>` to C code by using `Box<T>` as the type on the Rust side, and
70-
//! `T*` as the corresponding type on the C side. As an example, consider this
71-
//! C header which declares functions that create and destroy some kind of
72-
//! `Foo` value:
66+
//! So long as `T: Sized`, a `Box<T>` is guaranteed to be represented
67+
//! as a single pointer and is also ABI-compatible with C pointers
68+
//! (i.e. the C type `T*`). This means that if you have extern "C"
69+
//! Rust functions that will be called from C, you can define those
70+
//! Rust functions using `Box<T>` types, and use `T*` as corresponding
71+
//! type on the C side. As an example, consider this C header which
72+
//! declares functions that create and destroy some kind of `Foo`
73+
//! value:
7374
//!
7475
//! ```c
7576
//! /* C header */
@@ -108,6 +109,14 @@
108109
//! is to only use `Box<T>` for pointers that originated from the global
109110
//! allocator.
110111
//!
112+
//! **Important.** At least at present, you should avoid using
113+
//! `Box<T>` types for functions that are defined in C but invoked
114+
//! from Rust. In those cases, you should directly mirror the C types
115+
//! as closely as possible. Using types like `Box<T>` where the C
116+
//! definition is just using `T*` can lead to undefined behavior, as
117+
//! described in [rust-lang/unsafe-code-guidelines#198][ucg#198].
118+
//!
119+
//! [ucg#198]: https://github.com/rust-lang/unsafe-code-guidelines/issues/198
111120
//! [dereferencing]: ../../std/ops/trait.Deref.html
112121
//! [`Box`]: struct.Box.html
113122
//! [`Global`]: ../alloc/struct.Global.html

0 commit comments

Comments
 (0)