Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::{
- alloc::{alloc, dealloc, Layout},
- ops::Deref,
- };
- fn use_1(it: &Heap) {
- // some complicated logic
- drop(it); // we're done with it
- }
- fn use_2(it: &Heap) {
- // some complicated logic
- drop(it); // we're done with it
- }
- fn main() {
- let it = Heap::new(0);
- // some complicated logic
- use_1(&it);
- // some complicated logic
- use_2(&it);
- // some complicated logic
- drop(it); // we're done with it
- }
- struct Heap(*mut u8);
- impl Heap {
- fn new(it: u64) -> Self {unsafe{
- let ptr = alloc(Layout::new::<u64>());
- *(ptr as *mut _) = it;
- Heap(ptr)
- }}
- }
- impl Deref for Heap {
- type Target = u64;
- fn deref(&self) -> &u64 {unsafe{
- &*(self.0 as *mut u64)
- }}
- }
- impl Drop for Heap {
- fn drop(&mut self) {unsafe{
- dealloc(self.0, Layout::new::<u64>());
- }}
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement