本文简要介绍rust语言中 Function std::ptr::drop_in_place 的用法。 用法 pub unsafe fn drop_in_place<T>(to_drop: *mut T) where T: ?Sized, 执行指向值的析构函数(如果有)。 这在语义上等同于调用 ptr::read 并丢弃结果,但具有以下优点: 这是必需的使用drop_in_place删除未调整大小的类型(例如...
虚表header 中的drop_in_place是一个函数指针,其指向的函数能够原地 drop 当前胖指针所引用的对象。size和align两个域分别给出对象的大小和内存对齐,这两个域共同构成一个std::alloc::Layout结构,可用于释放当前胖指针所引用的对象所占据的内存。虚表 header 的存在使得 trait object 总是能被销毁和释放。例如当销...
我可以稍后致电ManuallyDrop::drop(&mut *ptr)手动删除该值。 我还可以取消引用该ManuallyDrop<Box<T>>元素,将原始指针保存到Box<T>,然后调用std::ptr::drop_in_place(box_ptr)。这应该会破坏Box自身并删除堆分配的T. 看看ManuallyDrop::drop实现,看起来它们实际上在做完全相同的事情。由于ManuallyDrop它的成本...
intrinsics::drop_in_place<T: ?Sized>(to_drop: * mut T) 在某些情况下,可能会将变量设置成不允许编译器自动调用变量的drop函数, 此时若是仍需要对变量调用drop,则在代码中显式调用此函数以出发对T类型的drop调用。 intrinsics::forget<T: ?Sized> (_:T) 代码中调用这个函数后,编译器不对forget的变量自...
unsafe { core::ptr::drop_in_place(inner) }; // SAFETY: The pointer was initialised from the result of a call to `alloc`. unsafe { dealloc(self.ptr.cast().as_ptr(), layout) }; } } } 实现Drop trait,同样直接通过 bindings::refcount_dec_and_test 调用内核 refcount_dec_and_test ...
fnmain(){letb=Box::into_raw(Box::new(A));leto=unsafe{Box::from_raw(b)};}structA;implDropforA{fndrop(&mutself){println!("dropA");}} 将裸指针还原为 Box 后,Box释放内存就释放。 2. 直接释放裸指针 usestd::{alloc::{dealloc,Layout},ptr::drop_in_place,};structA;implDropforA{fn...
core::ptr::drop_in_place<alloc::string::String>: push rax call qword ptr [rip + core::ptr::drop_in_place<alloc::vec::Vec<u8>>@GOTPCREL] pop rax ret core::ptr::drop_in_place<alloc::vec::Vec<u8>>: sub rsp, 24 mov qword ptr [rsp], rdi ...
std::ptr::drop_in_place(p); std::alloc::dealloc(p * , Layout::new::<M>()); } my_speed: <M> = ::new(M{id:.to_owned()}); my_speed_ptr: * M = & *my_speed; } 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. ...
// SAFETY: The value stored in inner is valid. unsafe { core::ptr::drop_in_place(inner) }; // SAFETY: The pointer was initialised from the result of a call to `alloc`. unsafe { dealloc(self.ptr.cast().as_ptr(), layout) }; ...
Code #![feature(inline_const, const_type_id)] use std::alloc::Layout; use std::any::TypeId; use std::mem::transmute; use std::ptr::drop_in_place; pub struct VTable { layout: Layout, type_id: TypeId, drop_in_place: unsafe fn(*mut ()), } i...