About resource ownership
Why does C++ have a const
keyword?
const
can prevent mistakes without runtime overhead
const
is even faster than non-const
!const
is about mutability: When is something allowed to change?
Why is resource exhaustion a bigger problem for systems programming than for applications programming?
malloc
, free
, fopen
, fclose
etc.)cannot borrow `v` as mutable because it is also borrowed as immutable
&T
&mut T
Vec::push
:fn push(&mut self, element: T)
Compiles or doesn’t compile?
Doesn’t compile:
cannot borrow `v` as mutable because it is also borrowed as immutable
Compiles or doesn’t compile?
Doesn’t compile, but for a different reason:
missing lifetime specifier
this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `arg1` or `arg2`
first
returns a borrow that comes from both arg1
and arg2
and lives as long as both arg1
and arg2
”fn first<'a, T>(
arg1: &'a Vec<T>,
arg2: &'a Vec<T>
) -> &'a T {
&arg1[0]
}
fn main() { // 'm (lifetime of main) ------
let mut vec1 = vec![1, 2, 3, 4]; // |
let mut vec2 = vec![1, 2, 3, 4]; // |
let p = first(&vec1, &vec2); // |
// |
vec2.push(41); // |
println!("{}", p); // |
} // --------------------------------------
fn first<'a, T>(
arg1: &'a Vec<T>,
arg2: &'a Vec<T>
) -> &'a T {
&arg1[0]
}
fn main() { // 'm (lifetime of main) ------
let mut vec1 = vec![1, 2, 3, 4]; // |
let mut vec2 = vec![1, 2, 3, 4]; // |
let tmp1 = &vec1; // |
let tmp2 = &vec2; // |
let p = first(tmp1, tmp2); // |
// |
vec2.push(41); // |
println!("{}", p); // |
} // --------------------------------------
struct
and enum
:struct
and enum
:More on borrow checking once we talk about memory