tezvyn:

Copy-on-write and implementing it for a custom struct

Source: interviewintermediate

WHAT IT TESTS: value semantics with shared backing storage. OUTLINE: CoW shares a buffer until mutation, deep-copying only when the buffer is non-unique; Array, Dictionary, Set, String use it; implement with a class storage box and isKnownUniquelyReferenced.

WHAT IT TESTS: how value types can avoid eager deep copies. ANSWER OUTLINE: copy-on-write keeps value semantics while sharing one heap buffer across copies; a deep copy happens only when you mutate a buffer referenced by more than one owner. Array, Dictionary, Set, and String use it. To implement it for a struct, store data in a private class instance and, before any mutation, check isKnownUniquelyReferenced and clone the storage if it is shared. RED FLAG: assuming plain structs get CoW for free.

Read the original → interview

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.

Copy-on-write and implementing it for a custom struct · Tezvyn