Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

재귀적인 해제 동작 막기: ManuallyDrop? #3

Open
nomicon-kr opened this issue Sep 28, 2024 · 0 comments
Open

재귀적인 해제 동작 막기: ManuallyDrop? #3

nomicon-kr opened this issue Sep 28, 2024 · 0 comments

Comments

@nomicon-kr
Copy link
Owner

destructors.md 에서 마지막 코드 섹션이 좀 이상하다. 이렇게 쓸 필요가 있나? 이렇게 써도 되지 않을까?

#![feature(allocator_api, ptr_internals)]

use std::alloc::{Allocator, Global, Layout};
use std::mem::ManuallyDrop;
use std::ptr::{drop_in_place, NonNull, Unique};

struct MyBox<T> {
    ptr: Unique<T>,
}

impl<T> Drop for MyBox<T> {
    fn drop(&mut self) {
        unsafe {
            drop_in_place(self.ptr.as_ptr());
            let c: NonNull<T> = self.ptr.into();
            Global.deallocate(c.cast(), Layout::new::<T>());
        }
    }
}

struct SuperBox<T> {
    my_box: ManuallyDrop<MyBox<T>>,
}

impl<T> Drop for SuperBox<T> {
    fn drop(&mut self) {
        unsafe {
            let c: NonNull<T> = self.my_box.ptr.into();
            Global.deallocate(c.cast(), Layout::new::<T>());
        }
    }
}
fn main() {}

일단 보이기로는 ManuallyDrop이 재귀적인 해제를 막아주는 것처럼 보인다...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant