DeveloperBreeze

Overview

In C++, copying objects can lead to serious bugs if you're dealing with raw pointers. By default, C++ uses shallow copy, which means only the pointer's value is copied—not the data it points to.

This tutorial covers:

  • What shallow vs deep copy means
  • The problems caused by shallow copy
  • How to implement deep copy correctly
  • A practical class example with dynamic memory
  • When to use Rule of Three vs Rule of Five

What Is Shallow Copy?

A shallow copy copies the values of member variables as-is. If your class has a pointer member, both the original and copy point to the same memory.

class Shallow {
public:
    int* data;

    Shallow(int val) {
        data = new int(val);
    }

    ~Shallow() {
        delete data;
    }
};

Now consider:

Shallow a(10);
Shallow b = a;  // default copy constructor

This causes both a.data and b.data to point to the same memory. When both destructors run, delete is called twice on the same pointer — undefined behavior!


What Is Deep Copy?

A deep copy duplicates the actual data pointed to, not just the pointer.

class Deep {
public:
    int* data;

    Deep(int val) {
        data = new int(val);
    }

    // Copy constructor for deep copy
    Deep(const Deep& other) {
        data = new int(*other.data);
    }

    // Assignment operator for deep copy
    Deep& operator=(const Deep& other) {
        if (this != &other) {
            delete data;
            data = new int(*other.data);
        }
        return *this;
    }

    ~Deep() {
        delete data;
    }
};

Rule of Three

If your class handles dynamic memory:

  • Copy Constructor
  • Copy Assignment Operator
  • Destructor

You must implement all three. This is called the Rule of Three.


Example: Deep Copy for a String Wrapper

class String {
private:
    char* buffer;

public:
    String(const char* str) {
        buffer = new char[strlen(str) + 1];
        strcpy(buffer, str);
    }

    // Copy constructor
    String(const String& other) {
        buffer = new char[strlen(other.buffer) + 1];
        strcpy(buffer, other.buffer);
    }

    // Assignment operator
    String& operator=(const String& other) {
        if (this != &other) {
            delete[] buffer;
            buffer = new char[strlen(other.buffer) + 1];
            strcpy(buffer, other.buffer);
        }
        return *this;
    }

    ~String() {
        delete[] buffer;
    }

    void print() const {
        std::cout << buffer << std::endl;
    }
};

Usage

String a("Hello");
String b = a;       // deep copy
String c("World");
c = a;              // deep assignment

All objects manage their own memory independently.


Modern C++: Rule of Five

In C++11 and newer, also consider:

  • Move Constructor
  • Move Assignment Operator

This is the Rule of Five. Add move semantics if your class is performance-sensitive and uses resource ownership.


Conclusion

When your class uses raw pointers:

  • Avoid shallow copies.
  • Always implement deep copy logic.
  • Follow the Rule of Three (or Rule of Five).
  • Prefer std::string, std::vector, or smart pointers in modern C++.

Understanding deep copy is essential for writing robust, bug-free C++ code.

Continue Reading

Discover more amazing content handpicked just for you

Tutorial

Avoiding Memory Leaks in C++ Without Smart Pointers

void loadData() {
    char* buffer = new char[1024];
    try {
        if (someCondition()) {
            throw std::runtime_error("Something went wrong");
        }
        // more code...
    } catch (...) {
        delete[] buffer;
        throw;
    }
    delete[] buffer;
}

Not elegant. Easy to forget or misplace deletes. Let's go better.

Apr 11, 2025
Read More
Tutorial

Implementing a Domain-Specific Language (DSL) with LLVM and C++

We’ll implement a recursive-descent parser that constructs an Abstract Syntax Tree (AST) from tokens. Our grammar is defined with standard operator precedence:

expression → term ((‘+’ | ‘-’) term)*
term       → factor ((‘*’ | ‘/’) factor)*
factor     → Number | ‘(’ expression ‘)’

Feb 12, 2025
Read More
Article
javascript

20 Useful Node.js tips to improve your Node.js development skills:

No preview available for this content.

Oct 24, 2024
Read More
Tutorial
javascript

Advanced JavaScript Tutorial for Experienced Developers

    function setupEventHandlers() {
        const message = 'Button clicked!';

        document.getElementById('myButton').addEventListener('click', () => {
            alert(message);
        });
    }

    setupEventHandlers();

Here, the click event handler forms a closure over the message variable, allowing it to be accessed when the button is clicked, even though setupEventHandlers has finished executing.

Sep 02, 2024
Read More
Tutorial
bash

Optimizing System Performance with Linux Kernel Parameters

   sudo sysctl -w kernel.sched_latency_ns=20000000
  • net.core.netdev_max_backlog:

Aug 19, 2024
Read More
Tutorial
csharp

Developing a Real-Time Multiplayer Game with Unity and C#

Congratulations! You've developed a basic real-time multiplayer game using Unity and C#. This tutorial covered setting up the project, implementing player movement, synchronizing actions, managing game state, and optimizing network performance. With these foundations, you can expand your game with more complex features, such as different game modes, AI opponents, or matchmaking systems.

This tutorial should provide a solid foundation for developing real-time multiplayer games with Unity and C#.

Aug 14, 2024
Read More
Code
csharp

Unity Inventory System using Scriptable Objects

No preview available for this content.

Aug 12, 2024
Read More
Code
csharp

Unity Player Controller Blueprint

  • Animation Integration: Add animator components and trigger animations based on movement and jump states.
  • Advanced Physics: Integrate more complex physics interactions, such as slopes or surface friction.
  • Networking: Adapt the controller for multiplayer environments using Unity’s networking solutions.

Aug 12, 2024
Read More
Code
csharp

Calculate Sum of Numbers in Array

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!