温馨提示×

c++浅拷贝和深拷贝怎么实现

c++
小亿
92
2023-11-22 05:08:44
栏目: 编程语言

浅拷贝和深拷贝是针对对象的拷贝操作而言的。

浅拷贝:浅拷贝是指仅仅拷贝对象的值,而不拷贝对象所指向的内存。这样,在拷贝对象和原始对象中会有一个指针指向同一块内存。如果拷贝对象和原始对象中的指针指向的内存被释放,那么两个对象将指向同一块无效内存,可能会导致程序出错。

实现浅拷贝的方式主要有两种:

  1. 默认的拷贝构造函数和赋值运算符:C++会自动生成默认的拷贝构造函数和赋值运算符,它们会按位拷贝对象的值。这种方式进行的拷贝就是浅拷贝。
class MyClass {
public:
    int *data;
    int size;

    // 默认的拷贝构造函数
    MyClass(const MyClass& other) {
        size = other.size;
        data = other.data;
    }

    // 默认的赋值运算符
    MyClass& operator=(const MyClass& other) {
        if (this != &other) {
            size = other.size;
            data = other.data;
        }
        return *this;
    }
};
  1. 自定义拷贝构造函数和赋值运算符:如果需要实现特定的拷贝操作,可以自定义拷贝构造函数和赋值运算符,进行浅拷贝。
class MyClass {
public:
    int *data;
    int size;

    // 自定义的拷贝构造函数
    MyClass(const MyClass& other) {
        size = other.size;
        data = other.data;
    }

    // 自定义的赋值运算符
    MyClass& operator=(const MyClass& other) {
        if (this != &other) {
            size = other.size;
            data = other.data;
        }
        return *this;
    }
};

深拷贝:深拷贝是指在拷贝对象时,会重新分配一块内存,并将原始对象所指向的内存内容拷贝到新的内存中。这样,在拷贝对象和原始对象中就没有指针指向同一块内存,修改拷贝对象不会影响原始对象。

实现深拷贝的方式主要有两种:

  1. 自定义拷贝构造函数和赋值运算符:在自定义拷贝构造函数和赋值运算符时,需要手动分配新的内存,并将原始对象所指向的内存内容拷贝到新的内存中。
class MyClass {
public:
    int *data;
    int size;

    // 自定义的拷贝构造函数
    MyClass(const MyClass& other) {
        size = other.size;
        data = new int[size];
        std::copy(other.data, other.data + size, data);
    }

    // 自定义的赋值运算符
    MyClass& operator=(const MyClass& other) {
        if (this != &other) {
            size = other.size;
            delete[] data;
            data = new int[size];
            std::copy(other.data, other.data + size, data);
        }
        return *this;
    }

    // 析构函数
    ~MyClass() {
        delete[] data;
    }
};
  1. 使用智能指针:C++11引入了智能指针(如std::shared_ptr、std::unique_ptr),可以自动管理动态分配的内存,避免手动释放内存的麻烦。
class MyClass {
public:
    std::shared_ptr<int> data;
    int size;

    // 自定义的拷贝构造函数
    MyClass(const MyClass& other) {
        size = other.size;
        data = std::make_shared<int[]>(size);
        std::copy(other.data.get(), other.data.get() + size, data.get());
    }

    // 自定义的赋值运算符
    MyClass& operator=(const MyClass& other) {
        if

0