//
// Created by yudw on 2017/8/6.
//
#ifndef MYFISTAPP_MYSTRING_H
#define MYFISTAPP_MYSTRING_H
#include <cstring>
namespace yudw
{
class MyString
{
public:
MyString(
const char *data =
nullptr)
; // 构造
MyString(
const MyString &rhs)
; // 拷贝构造
MyString(MyString&& rhs)
noexcept; // 移动构造
MyString&
operator = (
const MyString &rhs)
; // 赋值构造
MyString&
operator = (MyString&& rhs)
noexcept; // 移动赋值
~MyString()
; // 析构
size_t size()
const; // 获取sieze
const char* c_str()
const;
private:
char* data_
;
}
;
// 构造
MyString::MyString(
const char *data)
{
if(data ==
nullptr)
{
data_ =
new char[
1]
;
data_[
0] =
'\0';
}
else
{
data_ =
new char[strlen(data) +
1]
;
strcpy(data_
, data)
; // strcpy 里已经把\0赋值
}
}
// 拷贝构造
MyString::MyString(
const MyString &rhs)
{
data_ =
new char[strlen(rhs.data_) +
1]
;
strcpy(data_
, rhs.data_)
;
}
// 移动构造 std::move
MyString::MyString(MyString &&rhs)
noexcept
{
data_ = rhs.data_
;
rhs.data_ =
nullptr;
}
// 赋值构造函数
MyString& MyString::
operator=(
const MyString &rhs)
{
if(
this == &rhs)
{
return *
this;
}
MyString temp(rhs)
;
std::swap(data_
, rhs.data_)
;
return *
this;
}
// c++ primer 的一种写法, c++ 11的写法(推荐写法)
MyString& MyString::
operator=(MyString rhs)
{
std::swap(data_
, rhs.data_)
;
return *
this;
}
// 移动赋值
MyString& MyString::
operator=(MyString &&rhs)
{
if(
this != &rhs)
{
delete [] data_
; // 释放原有空间
data_ = rhs.data_
; // 赋值
rhs.data_ =
nullptr; // 清空
}
return *
this;
}
// 析构函数
MyString::~MyString()
{
delete[] data_
;
// delete data_;
}
// 获取size
size_t MyString::size()
const
{
return strlen(data_)
;
}
// 获取c_str
const char* MyString::c_str()
const
{
return data_
;
}
}
#endif //MYFISTAPP_MYSTRING_H