15 构造函数与析构函数(五)

深拷贝与浅拷贝

//String.h
#ifndef _STRING_H_
#define _STRING_H_

class String
{
public:
    String(char* str="");
    ~String();
    String(const String& other);
    String& operator=(const String& other);



    void Display();

private:
    char* AllocAndCpy(char* str);

    char* str_;
};

#endif // _STRING_H_

//String.cpp
#include "String.h"
//#include <string.h>
#include <cstring>
#include <iostream>
using namespace std;

String::String(char* str/* = */)
{
    str_ = AllocAndCpy(str);
}

String::~String()
{
    delete[] str_;
}

String::String(const String& other)
{
    str_ = AllocAndCpy(other.str_);
}

String& String::operator =(const String &other)
{
    if (this == &other)
        return *this;

    delete[] str_;//销毁空间,之后再深拷贝
    str_ = AllocAndCpy(other.str_);
    return *this;
}

char* String::AllocAndCpy(char* str)
{
    int len = strlen(str) + 1;
    char* tmp = new char[len];
    memset(tmp, 0, len);
    strcpy(tmp, str);
    return tmp;
}

void String::Display()
{
    cout<<str_<<endl;
}

//main.cpp
#include "String.h"

int main(void)
{
    String s1("AAA");
    s1.Display();
    String s2 = s1;     // 调用拷贝构造函数
                        // 系统提供的默认拷贝构造函数实施的是浅拷贝 s2.str_ = s1.str_,两个指针指向同一块内存,析构时这块内存释放了两次,会报错

    String s3;
    s3.Display();
    s3 = s2;            // 调用等号运算符
                        // 系统提供的默认等号运算符实施的是浅拷贝 s3.str_ = s2.str_;
                        // s3.operator=(s2);

    // 要让对象是独一无二的,我们要禁止拷贝
    // 方法是将拷贝构造函数与=运算符声明为私有,并且不提供它们的实现
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值