Cheatsheet: Data Structures
    Array / List
    Map / Dict
    Set
    Tuple
    Struct / Data Class
    Stacks
    Other Data Structures
    Collection Conversions
Cheatsheet: Control Flow
Cheatsheet: Class

Polyglot CheatSheet - Memory Management

Updated: 2021-11-19

Memory management, pointers and references.

C++

NO garbage collector.

// use stack
char a = 'a';
// no need to free a

// use heap
char *b = new char('b');
delete b;

Smart pointers:

// memory freed when ptr_a goes out of scope
unique_ptr<char> ptr_a(new char('a'));

// reference counted pointer
shared_ptr<char> ptr_b(new char('b'));

// pointer that does not increase reference counts
weak_ptr<char> ptr_c = ptr_b;

// memory freed when ptr_d goes out of scope
// differs from unique_ptr in copy semantics
auto_ptr<char> ptr_d(new char('d'));

Rust

NO garbage collector.

// use stack
let a: char = 'a';

// use heap
let b = Box::new('b');

// b will be freed when it is out of scope
// or force free by mem::drop
mem::drop(b);

// reference counted pointer
let rc = Rc::new('c');

// atomically reference counted pointer
// can be safely used across threads
let arc = Arc::new('d');

Java

With garbage collection.

// use stack
char a = 'a';

// use heap
Character b = new Character('b');

// no way to free a or b, will be garbage collected

// reference that does not impact garbage collection
WeakReference<Character> weakRef = new WeakReference<>(ref);

// soft reference
SoftReference<Character> softRef = new SoftReference<>(ref);

All soft references to softly-reachable objects are guaranteed to be cleared before a JVM throws an OutOfMemoryError.