String类的深拷贝

本文介绍了一个使用C++实现的自定义字符串类String。该类采用深拷贝和标准交换(idiom)等技术来确保资源管理的安全性,并提供了下标操作符及C字符串转换接口。此外,还展示了构造函数、析构函数以及赋值操作符的现代实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class String
{
public:
    String(char* str="")
        :_str(new char[strlen(str)+1])
    {
        cout << "String()" << endl;
        memcpy(_str, str, sizeof(char)*(strlen(str) + 1));
    }
    ~String()
    {
        if (_str)
        {
            delete[] _str;
        }
        cout << "~String()" << endl;
    }
    //传统写法
    //String(const String& s)
    //  :_str(new char[strlen(s._str)+1])
    //{
    //  strcpy(_str, s._str);
    //}
    //String& operator=(const String& s)
    //{
    //  if (this != &s)
    //  {
    //      char* tmp = new char[strlen(s._str) + 1];
    //      delete[] _str;
    //      strcpy(tmp, s._str);
    //      _str = tmp;
    //  }
    //  return *this;
    //}
    //现代写法
    String(const String& s)
        :_str(NULL)
    {
        String tmp(s._str);
        std::swap(_str, tmp._str);
    }
 
    //String& operator=(const String& s)
    //{
    //  if (this != &s)//不能写成if ((*this) != s),因为左右类型不匹配,移位一个为String一个为cosntString
    //  {
    //      String tmp(s);
    //      std::swap(_str, tmp._str);
    //  }
    //  return *this;
    //}
    String& operator=( String s)//加cosnt也不行,两边类型不匹配,c++要格外小心cosnt
    {
        std::swap(_str, s._str);
        return *this;
    }
public:
 
    char& operator[](int index)
    {
        return _str[index];
    }
    char* C_str()
    {
        return _str;
    }
private:
    char* _str;
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值