拷贝构造函数及赋值运算的问题

本文通过一个C++示例程序详细解释了浅复制和深复制的区别,展示了当对象包含指向动态分配内存的指针时,如果不正确地处理拷贝构造函数和赋值运算符,将导致的问题及解决方案。


#include <iostream>
using namespace std;

class Test
{
public:
    explicit Test( int init = 0 )
    {   
        pStore = new int(init);
    }   

    int read() const
    {   
        return *pStore;
    }   

    void write(int x)
    {   
        *pStore = x;
    }   
private:
    int *pStore;
};

int main()
{
    Test test1(2);
    Test test2 = test1;
    Test test3;
        
    test3 = test2;
    test1.write(4);
    cout << test1.read() << endl
         << test2.read() << endl
         << test3.read() << endl;
    return 0;
}
                                                                                                                                                                                                                

输出:

4

4

4

 

由于使用默认的拷贝构造函数和赋值运算符,输出结果不为想象中的4,2,2。

程序存在的问题:

浅复制:指针被复制而不是指针所指的内容被复制

 

在 test3 = test2 之前:

test1.pStore == test2.pStore

test3 = test2 后

test1.pStore == test2.pStore == test3.pStore

 

内存泄露:test1 与 test3分配的内存都没有得到释放

 

解决方法:添加三个函数

    ~ Test()
    {
        delete pStore;
    }
    const Test & operator=( const Test & rtest )
    {
        if ( this != &rtest )
            *pStore = *rtest.pStore;
        return *this;
    }
    Test( const Test &rtest)
    {
        pStore = new int(*rtest.pStore);
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值