ECS 36A Lecture Notes - Lecture 20: Call Stack, Compile Time, Time Complexity

147 views3 pages
4 Dec 2018
ECS 36A - Lecture 20 - Ownership, Borrowing, and Lifetime #2
Broken Lifetime Examples:
let x;
{ #start of y’s lifetime
let y = 0:
x = &y #x references y here
} #end of y’s lifetime, x references nothing anymore
println!(“{ }”, x) # x outlives y so this cannot be done
fn f() → &i32 {
let x = 0; #lifetime of x is within the function, x lives on a stack
&x #when the function returns this reference, the def of x doesn’t exist
let p = f() # at this point x has disappeared bc stack frame for f disappeared, no reference
FIX for these:
fn f() → &i32 {
let x = 0
x #return the VALUE instead of a reference, or put the reference on a heap
let p = f()
Advantage of returning value: avoids lifetime errors
Advantage of returning a reference: avoid a copy of the value, only copy the pointer
Use of pointers: if you have 1 GB of data in f() -- would not want to copy it all, would rather
want to return a pointer for each value
let x = 0;
let y = &x;
let z = &x; # legal to do
# may have multiple shared references to the same valuable, allow you to read only
# multiple readers on the same object have no harm to it
let x = 0; #tells us that x is not mutable, meaning cannot write to x
let y = &mut x; #illegal, mutates x through y
Advantage of immutable variables: allows compiler to do aggressive optimization, reduces
programming errors (cannot accidentally modify it later) → if you have an option, make it
Unlock document

This preview shows page 1 of the document.
Unlock all 3 pages and 3 million more documents.

Already have an account? Log in

Get OneClass Notes+

Unlimited access to class notes and textbook notes.

YearlyBest Value
75% OFF
$8 USD/m
$30 USD/m
You will be charged $96 USD upfront and auto renewed at the end of each cycle. You may cancel anytime under Payment Settings. For more information, see our Terms and Privacy.
Payments are encrypted using 256-bit SSL. Powered by Stripe.