C++之拷贝构造函数、深拷贝、浅拷贝

C++拷贝构造与深浅拷贝
本文深入解析C++中拷贝构造函数的作用及其自动调用机制,并通过具体示例说明深拷贝与浅拷贝的区别,强调在涉及动态内存分配时正确实现拷贝构造的重要性。
 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
 
/*
    CopyConstructor.cpp
    Author: Michael Joessy
    Date: 2017-06-07
    Marks:
    如果没有自定义拷贝构造函数,则系统会自动生成一个默认的拷贝构造函数(什么也不输出)。
    当采用直接初始化或复制初始化实例化对象时,系统自动调用拷贝构造函数。

    对象间的拷贝分为:深拷贝 和 浅拷贝
    浅拷贝:只是将数据成员的值进行了拷贝
    深拷贝:涉及到指针时,特别注意!
    在某些状况下,类内成员变量需要动态开辟堆内存,如果实行浅拷贝,如A = B。
    这时,如果B中有一个成员变量指针已经申请了内存,那A中的那个成员变量也指向同一块内存。
    这就出现了问题:当B把内存释放了(如:析构),这时A内的指针就是野指针了,出现运行错误。
*/


#include <iostream>
#include <string>
using namespace std;


class Student
{
public:
    
//无参构造函数,即默认构造函数
    Student()
    {
        cout << 
"Student" << endl;
    }
    
//定义拷贝构造函数
    //定义格式:类名(const 类名& 变量名)
    Student(const Student &stu)
    {
        cout << 
"Copy Student" << endl;
    }
protected:
private:
    string m_strName;
};


/* 深拷贝和浅拷贝可以简单理解为:
    如果一个类拥有资源,当这个类的对象发生复制过程的时候,资源重新分配,这个过程就是深拷贝;
    反之,没有重新分配资源,就是浅拷贝。
*/

class MyArray
{
public:
    MyArray()
    {
        m_nCount = 
5;
        m_pArr = 
new int[m_nCount];
    }
    MyArray(
const MyArray &arr)
    {
        m_nCount = arr.m_nCount;
        
//m_pArr = arr.m_pArr;          //浅拷贝,隐患大
        m_pArr = new int[m_nCount];     //深拷贝,重新申请另一块内存
        for (int i = 0; i < m_nCount; i++)
        {
            m_pArr[i] = arr.m_pArr[i];
        }
    }
protected:
private:
    
int m_nCount;
    
int *m_pArr;
};

int main(void)
{
    
//拷贝构造函数
    Student std1;
    Student std2 = std1;
    Student std3(std1);

    
//深拷贝和浅拷贝
    MyArray arr1;
    MyArray arr2 = arr1;

    cin.get();
    
return 0;
}

转载于:https://www.cnblogs.com/MakeView660/p/6957502.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值