Rustコトハジメ

プログラミング言語Rustに関する情報をお届けします。

Smart pointers in Rust

https://www.rustforbeginners.com/entry/en/2018/12/29www.rustforbeginners.com

In the post above, I mentioned the Vec is a ownership pointer that has three members.

In Rust, pointer-like stuffs which has internal special metadata are called smart pointers.

Smart pointers in Rust are such as:

  • Heap management: Box
  • Reference counting: Rc, Weak, Arc
  • Guard: Ref, RefMut, MutexGuard, RwLockReadGuard, RwLockWriteGuard

The special thing about smart pointers is that hey have special metadata and special Drop implementation and Deref and DerefMut implementations (if posssble) for ergonomics.

For example, MutexGuard's Drop unlocks the lock structure in the internal metadata.

impl<'a, T: ?Sized> Drop for MutexGuard<'a, T> {
    #[inline]
    fn drop(&mut self) {
        unsafe {
            self.__lock.poison.done(&self.__poison);
            self.__lock.inner.raw_unlock();
        }
    }
}

If you have a C++ programmer, you can find this is the same in C++.

void safe_increment()
{
    std::lock_guard<std::mutex> lock(g_i_mutex);
    ++g_i;
 
    std::cout << std::this_thread::get_id() << ": " << g_i << '\n';
 
    // g_i_mutex is automatically released when lock
    // goes out of scope
}

And yes, Rust just generalizes the idea into language level by defining traits.

Smart pointers in C++ are such as

  • unique_ptr
  • shared_ptr
  • weak_ptr

and they are counterparts of Box, Rc and Weak in Rust. This is also a generalization of separate concepts in C++ into a single concept called small pointers in Rust.