mystring类的实现

mystring.h文件

#ifndef _CMYSTRING_H_
#define _CMYSTRING_H_

#include <iostream>
#include <cstring>

class CMyString
{
public: //default ctor
    CMyString(const char *s = nullptr)
    {
        if (!s)
        {
            _data = new char[1];
            *_data = '\0';
            return;
        }
        _data = new char[strlen(s) + 1];
        strcpy(_data, s);
    }
    //copy ctor
    CMyString(const CMyString &other)
    {
        _data = new char[strlen(other._data) + 1];
        strcpy(_data, other._data);
    }
    //dtor
    ~CMyString() 
    {
        delete [] _data;
    }
    //assign operator 
    CMyString& operator=(const CMyString &other)
    {
        if(this == &other)
            return *this;
        delete _data;
        _data = new char[strlen(other._data) + 1];
        strcpy(_data, other._data);
        return *this;
    }

    friend std::ostream& operator<<(std::ostream &os, const CMyString &s)
    {
        os << s._data;
        return os;
    } 

private:
    char *_data;
};

#endif

main.cpp文件

#include <iostream>
#include "mystring.h"

using namespace std;

int main(int argc, char *argv[])
{
    CMyString str1;
    CMyString str2("hello,world");
    CMyString str3(str2);
    CMyString str4("hi,world");
    str1 = str3 = str4;

    cout << str1 << " " << str2 << " " << str3 << " " << str4 << endl;

    return 0;
}

异常安全性

考虑赋值运算符中new会产生异常,为了写出异常安全性的代码,上面的代码有两种修改方案:
1. 先new,成功之后再delete掉,不成功则返回原来的状态
2. 先产生一个暂时的栈实例,然后交换两者的数据成员(字符指针),当跳出作用域后,栈实例销毁会销毁原来的数据成员

方案1

CMyString& operator= (const CMyString& other)
{
    if(this == &other)
        return *this;
    char *old_data = _data;
    _data = new char[strlen(other._data) + 1];
    if (!_data)
        return *this;
    delete old_data;
    strcpy(_data, other._data);

    return *this;
}

方案2

CMyString& operator=(const CMyString &other)
{
    CMyString tmp_str(other);
    char *tmp_data = tmp_str._data;
    tmp_str._data = _data;
    _data = tmp_data;

    return *this;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值