🧠 a. Copy-On-Write (COW)


#intuition

Copy-On-Write (COW) is an optimization strategy used to delay or avoid copying data until it is absolutely necessary — i.e., when a write operation happens.

Think of it like this:

“Let’s

share

modify


#use-case

Used in:


#syntax + #example

A simplified custom COW string class:

#include <iostream>
#include <string>
#include <memory>

class CowString {
private:
    struct StringData {
        std::string value;
        int refCount;
        StringData(const std::string& val) : value(val), refCount(1) {}
    };

    StringData* data;

    void detach() {
        if (data->refCount > 1) {
            // Perform deep copy
            --data->refCount;
            data = new StringData(data->value); // Deep copy
        }
        // If refCount == 1, already exclusive
    }

public:
    CowString(const std::string& val) {
        data = new StringData(val);
    }

    CowString(const CowString& other) {
        data = other.data;
        ++data->refCount;
    }

    ~CowString() {
        if (--data->refCount == 0)
            delete data;
    }

    void setChar(size_t index, char c) {
        detach(); // Ensure uniqueness before modification
        data->value[index] = c;
    }

    std::string get() const {
        return data->value;
    }
};

#output

CowString a("hello");
CowString b = a;    // Shared data
b.setChar(0, 'y');  // Deep copy on write

std::cout << a.get(); // prints: hello
std::cout << b.get(); // prints: yello