C++ 深拷贝与浅拷贝原理

2021-03-30  本文已影响0人  Dalvik_

1 拷贝构造函数执行流程
过程分析:对象赋值会调用拷贝构造函数

#include <iostream>
#include<string.h>

using namespace std;

class Student {
public:
    Student() { cout << "空参数构造函数" << endl; }

    Student(char *name, int age) {
        this->name = (char *) malloc(sizeof(char *) * 10);
        strcpy(this->name, name);
        // this->name = name;
        this->age = age;
        cout << "两个参数构造函数" << endl;
    }

    Student(char *name) : Student(name, 99) {
        cout << "一个参数构造函数" << endl;
    }

    ~Student() {
        cout << "析构函数" << endl;
    }

    Student(const Student &student1) {
        cout << "拷贝构造函数 &stu:" << &student1 << " this:" << this << endl;
        //【浅拷贝】:新地址name  旧地址name 指向同一个空间,会造成,重复free的问题,引发奔溃
        this->name = student1.name;
        this->age = student1.age;
    }

private:
    char *name;
    int age;
public:
    char *getName() {
        return this->name;
    }

    void setName(char *name) {
        this->name = name;
    }

    int getAge() {
        return age;
    }

    void setAge(int age) {
        this->age = age;
    }
};


Student getStudent(char *name) {
    Student stu(name); // 旧地址
    cout << "getStudent函数:" << &stu << endl; // 旧地址
    return stu; // stu 旧地址
} // 弹栈 释放 栈成员 stu

void showStudent(Student stu) { //执行拷贝构造函数 函数出栈 释放资源
    cout << "showStudent函数:" << &stu << "  " << stu.getName() << "," << stu.getAge() << endl;
}


int main() {
    Student student1;
    Student student2;
    cout << &student1 << endl;
    cout << &student2 << endl;
    cout << endl;
    Student student3("刘大海");
    Student student4 = student3; //会调用拷贝构造函数

    cout << &student3 << endl;
    cout << &student4 << endl;

    return 0;
}

输出:
空参数构造函数
空参数构造函数
0x61fd60
0x61fd50

空参数构造函数
拷贝构造函数
0x61fd40
0x61fd30
析构函数
析构函数
析构函数
析构函数

2.浅拷贝流程

Student(const Student &student1) {
        cout << "拷贝构造函数 &stu:" << &student1 << " this:" << this << endl;
        this->name = student1.name;
        this->age = student1.age;
    }

3.浅拷贝执行崩溃原因分析
多次释放资源会导致程序崩溃

void showStudent(Student stu) { //执行拷贝构造函数 函数出栈 释放资源
    cout << "showStudent函数:" << &stu << "  " << stu.getName() << "," << stu.getAge() << endl;
}
Student(const Student &student1) {
        cout << "拷贝构造函数 &stu:" << &student1 << " this:" << this << endl;
        //【浅拷贝】:新地址name  旧地址name 指向同一个空间,会造成,重复free的问题,引发奔溃
        this->name = student1.name;
        this->age = student1.age;
    }

4.深拷贝流程

 Student(const Student &student1) {
        cout << "拷贝构造函数 &stu:" << &student1 << " this:" << this << endl;
        //【浅拷贝】:新地址name  旧地址name 指向同一个空间,会造成,重复free的问题,引发奔溃
        // this->name = student1.name;

        // 【深拷贝】
        this->name = (char *) malloc(sizeof(char *) * 10);
        strcpy(this->name, name);
        this->age = student1.age;
    }

5.默认拷贝构造函数是浅拷贝
如果有堆成员变量,必须覆盖拷贝构造函数,实现深拷贝

上一篇 下一篇

猜你喜欢

热点阅读