Theo Lee
Box<T> vs Rc<T> vs Arc<T>
Thumbnail
by theolee72 Monday, Dec 1 2025
Rust's smart pointers (Box, Rc, Arc) enable efficient memory management by switching between different memory types. Box<T> handles heap storage, Rc<T> manages multiple owners via reference counting, and Arc<T> uses atomic operations for multi-threading. Each design balances ownership and performance to optimize memory usage.
like
0
reviews
0
share
0

Rust의 Smart pointer는 Box<T> -> Rc<T> -> Arc<T>로 이어지는 흐름을 가지고 있다. 각 smart pointer의 필요성 및 기능, 기능 구분 이유 등을 설명하며 왜 이렇게 설계되었는지 알아보자. 

smart pointer, 말 그대로 pointer는 pointer인데, 조금 똑똑한 pointer라는 것이다. 일반 pointer의 기능 포함 + 추가적인 metadata와 기능을 가지고 있다. 각 smart pointer의 기능들은 아래서 추가적으로 설명하겠다. smart pointer는 대부분 struct로 구현되어 있다. smart pointer도 pointer인 만큼 deref trait이 구현되어 있어 *p방식으로 값에 접근 가능하다. 또한 smart pointer는 보통 스코프 종료 시 리소스를 정리하는 책임까지 지기 때문에 drop trait이 구현되어 있다. 

가장 기본적인 smart pointer로 Box<T>, Rc<T>, Arc<T>가 있다. Box<T>가 가장 기능이 적고 갈 수록 많아진다. 하지만 당연히 기능과 성능의 tradeoff관계가 있다. smart pointer는 pointer로만 보기 아까운 부분이 있다. 사실 pointer보단 ownership을 가진 struct로 보는 편이 더 맞는거 같다. address를 들고 있으면서, 그 address에 있는 data의 ownership을 가진 container같은 것이다. 

Box<T>

Box<T>는 가장 기본적인 smart pointer로 data를 heap에 저장하고, stack에는 address만 남기는 smart pointer이다. Box<T>는 Rc<T>와 Arc<T>와 다르게 Rust compiler가 특별히 취급하는 native type이다.

Box<T>의 등장 배경

Rust의 규칙상 모든 변수의 크기는 compile time에 알아야 한다. 하지만 이런 경우 문제가 생긴다. 

enum List {
    Cons(i32, List),
    Nil,
}
use crate::List::{Cons, Nil};

fn main() {
    let list = Cons(1, Cons(2, Cons(3, Nil))); //컴파일 불가: 크기를 알 수 없음
}