How does Rust achieve compile-time-only pointer safety?

前端 未结 3 938
天命终不由人
天命终不由人 2021-02-02 15:31

I have read somewhere that in a language that features pointers, it is not possible for the compiler to decide fully at compile time whether all pointers are used correctly and/

3条回答
  •  甜味超标
    2021-02-02 15:36

    Most of the safety of Rust references is guaranteed by strict rules:

    • If you posses a const reference (&), you can clone this reference and pass it around, but not create a mutable &mut reference out of it.
    • If a mutable (&mut) reference to an object exists, no other reference to this object can exist.
    • A reference is not allowed to outlive the object it refers to, and all functions manipulating references must declare how the references from their input and output are linked, using lifetime annotations (like 'a).

    So in terms of expressiveness, we are effectively more limited than when using plain raw pointers (for example, building a graph structure is not possible using only safe references), but these rules can effectively be completely checked at compile-time.

    Yet, it is still possible to use raw pointers, but you have to enclose the code dealing with them in a unsafe { /* ... */ } block, telling to the compiler "Trust me, I know what I am doing here". That is what some special smart pointers do internally, such as RefCell, which allows you to have these rules checked at runtime rather than compile-time, to gain expressiveness.

提交回复
热议问题