스마트 포인터를 더 편리하게 사용하고, 메모리 관리를 자동화하기 위해 Deref와 Drop 이라는 두 트레잇을 제공함
스마트 포인터는 데이터를 힙에, 포인터를 스택에 저장함
이런 스마트 포인터가 일반 참조자처럼 동작하려면 Deref 트레잇을 구현해야 한다
출처: <https://doc.rust-lang.org/std/ops/trait.Deref.html>
use std::ops::Deref;
struct DerefExample<T> {
value: T
}
impl<T> Deref for DerefExample<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.value
}
}
fn main() {
let x = DerefExample { value: 'a' };
assert_eq!('a', *x); // *을 가능하게 하는 것이 Deref 트레잇
}
객체가 스코프를 벗어날 때 자동으로 정리 코드가 실행됨
struct CustomSmartPointer {
data: String,
}
impl Drop for CustomSmartPointer {
fn drop(&mut self) {
println!("메모리 해제: {}", self.data);
}
}
fn main() {
let c = CustomSmartPointer { data: String::from("Hello Rust") };
println!("CustomSmartPointer 생성됨!");
} // 여기서 c가 스코프를 벗어나면서 drop() 호출됨
[출력]
CustomSmartPointer 생성됨!
메모리 해제: Hello Rust