Section 1/91 menit

1. Masalah yang Dipecahkan

1. Masalah yang Dipecahkan

Implicit Copying: Nyaman tapi Berbahaya untuk Resources

Di Swift (dan hampir semua bahasa modern), value types di-copy secara implisit. Ini membuat kode mudah dan aman — untuk data biasa:

swift
var point1 = CGPoint(x: 1, y: 2)
var point2 = point1  // copy — tidak ada masalah, CGPoint adalah "data murni"
point2.x = 10
// point1.x masih 1 — aman

Tapi ada kategori nilai yang tidak boleh di-copy: resource handles, unique ownership tokens, dan objects dengan lifecycle yang ketat.

swift
// Swift 5: masalah ini tidak terdeteksi compiler
struct FileDescriptor {
    let fd: Int32
    
    func close() {
        Darwin.close(fd)
    }
}

let file = FileDescriptor(fd: open("/tmp/data.txt", O_RDONLY))
let copy = file  // COPY terjadi — dua FileDescriptor, satu fd yang sama!

file.close()     // menutup fd
copy.close()     // menutup fd yang SAMA lagi → undefined behavior (double close)

Double free, double close, use-after-free — semua ini adalah bug yang umum dan berbahaya, dan sebelumnya tidak bisa dicegah di level type system Swift.

Mengapa Ini Penting?

Kategori resource yang sering punya masalah ini:

  • File handles — harus ditutup tepat sekali
  • Database connections — harus dikembalikan ke pool tepat sekali
  • Network sockets — harus ditutup dengan benar
  • Mutex locks / critical section guards — harus di-release tepat sekali
  • Memory allocations — harus di-free tepat sekali
  • Kriptografi keys — harus di-clear dari memori tepat sekali
  • Transaction handles — harus di-commit atau di-rollback tepat sekali