String类的传统写法:
#include <iostream>
#include <assert.h>
class String{
String(const char* str = ""){
if (nullptr == str){
assert(false);
return;
}
_str = new char[strlen(str) + 1];
strcpy(_str, str);
}
String(const String& s)
:_str(new char[strlen(s._str) + 1])
{
strcpy(_str, s._str);
}
String& operator=(const String& s){
if (this != &s){
char* _pstr = new char[strlen(s._str) + 1];
strcpy(_pstr, s._str);
delete[] _str;
_str = _pstr;
}
return *this;
}
~String(){
if (_str){
delete[] _str;
_str = nullptr;
}
}
private:
char* _str;
};
String的现代写法:
#include <iostream>
#include <assert.h>
using namespace std;
class String{
String(const char* str = ""){
if (nullptr == str){
str = "";
}
_str = new char[strlen(str) + 1];
strcpy(_str, str);
}
String(const String& s)
:_str(nullptr)
{
String strtmp(s._str);
swap(_str, strtmp._str);
}
String& operator=( String s){
swap(_str, s._str);
return *this;
}
~String(){
if (_str){
delete[] _str;
_str = nullptr;
}
}
private:
char* _str;
};