In programming, unique pointers are a variation on pointers prioritising memory management. The object pointed to is disposed of when either the pointer is destroyed (goes out of scope) or the pointer is assigned to another object.
In C++
Since C++11, we can use std::unique_ptr<T>
. By default this can be re-assigned. If the pointer is const, then the object only exists for the scope of the pointer.
In Rust
The Rust memory ownership model largely means that the default pointer type (stack and heap) are unique pointers. For heap pointers, we can use Box<T>
. By default this is immutable (like the C++ const std::unique_ptr
) but we can specify a mutable pointer (i.e., the owner can be re-assigned, but the object isn’t destroyed — only moved) with mut
.