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;
}