C++ › Memory Management

What is the difference between shallow copy and deep copy in memory terms?

Advanced

Answer

A shallow copy copies pointer values, so two objects share the same heap memory—leading to double-free or dangling issues when one is destroyed. A deep copy allocates new memory and copies the pointed-to data, giving each object independent ownership. The Rule of Three/Five ensures correct copy/move semantics for classes managing resources.
// Deep copy in copy constructor
MyClass(const MyClass& o) : data(new int[o.n]), n(o.n) {
    std::copy(o.data, o.data + n, data);
}
Real-world example A class that shallow-copies a buffer double-frees it, crashing when both copies are destroyed.

Common follow-ups: What is the Rule of Three/Five? | Why does shallow copy cause double-free?