본문 바로가기
개발/러스트 (Rust)

Rust 기본, OBRM vs RAII

by 레조 2024. 7. 1.

https://rustacean.net/

 

Rust 기본 : 소유권 기반 리소스 관리 (OBRM : Ownership Based Resource Management)

 

Rust는 리소스를 컴파일러가 관리한다. (OBRM : Ownership Based Resource Management.)

C++은 <memory> 라이브러리로 패턴을 제공한다. (RAII : Resource Acquisition Is Initialization.)

 

Rust Box & Rc 스마트 포인터

struct Car {}

// Box : 힙 메모리의 ownership 전달 (=RAII 패턴 C++ unique_ptr)
let car = Box::new(Car {});
let car2 = car;
    
// 레퍼런스 카운트가 증가하고 같은 힙 메모리를 가리킨다. (=RAII 패턴 C++ shared_ptr)
let newCar = Rc::new(Car {});
let newCar2 = newCar.clone();
let my_string = String::from("LGR");

비교 1 : Rust Box vs C++ unique_ptr

 

Rust OBRM : Box 스마트 포인터 (Heap allocation)

struct Car {}

fn memory_example() {
    let car = Box::new(Car {});
    let car2 = car; // Rust 소유권 이동.
    function_that_can_panic();
    if !should_continue() { return; }
}

fn file_example() {
    let path = Path::new("example.txt");
    let file = File::open(&path).unwrap();
    function_that_can_panic();
    if !should_continue() { return; }
}

 

C++ RAII Pattern : unique_ptr

class Car {};

void memory_example()
{
    unique_ptr<Car> car = make_unique<Car>();
    unique_ptr<Car> car2 = move(car); // move 사용한 소유권 이동.
    function_that_can_throw();
    if(!should_continue()) return;
}

void file_example()
{
    File file = File("example.txt");
    function_that_can_throw();
    if(!should_continue()) return;
}

비교 2 : Rust Rc vs C++ shared_ptr

 

소유권 공유 (Shared Ownership) : 레퍼런스 카운트로 관리.

Rust OBRM : Rc smart pointer (Heap allocation)

struct Car {}

fn memory_example() {
    let car = Rc::new(Car {});
    let car2 = car.clone(); // 동일한 메모리 위치를 가리키는 새로운 스마트 포인터 생성. (명시적)
    function_that_can_panic();
    if !should_continue() { return; }
}

fn file_example() {
    let path = Path::new("example.txt");
    let file = File::open(&path).unwrap();
    function_that_can_panic();
    if !should_continue() { return; }
}

 

C++ RAII Pattern : shared_ptr

class Car {};

void memory_example()
{
    shared_ptr<Car> car = make_shared<Car>();
    shared_ptr<Car> car2 = car; // 동일한 메모리 위치를 가리키는 새로운 스마트 포인터 생성. (암시적)
    function_that_can_throw();
    if(!should_continue()) return;
}

void file_example()
{
    File file = File("example.txt");
    function_that_can_throw();
    if(!should_continue()) return;
}

보다 자세한 내용은 아래 두 영상을 보고 비교해보자.

 

C++ RAII Pattern.

https://www.youtube.com/watch?v=AnFaf-L_DfE

 

 

Rust OBRM

https://www.youtube.com/watch?v=7EcNkr6KFy0