CString的高效版本

#pragma once
#include <string>
template<class T>
void SwapFun(T& left, T& right)
{
 T temp = left;
 left = right;
 right = temp;
}
class CShString
{
public:
 CShString(char* pStr)
  :m_iLen(strlen(pStr))
  , m_iMaxSize(CalcuMax(m_iLen))
  , px(new char[m_iMaxSize])
  , pn(new int(1))
 {
  memcpy(px, pStr, m_iLen + 1);
 }
 CShString(char* pStr, int iLength)
  :m_iLen(iLength)
  , m_iMaxSize(CalcuMax(iLength))
  , px(new char[m_iMaxSize])
  , pn(new int(1))
 {
  ASSERT(iLength == strlen(pStr));
  memcpy(px, pStr, m_iLen);
  px[m_iLen] = '\0';
 }
 CShString(const CShString& strOther)
  : px (strOther.px), pn(strOther.pn);
 {
  ++*pn;
 }
 CShString& Assign(const CShString& other)
 {
  Swap(CShString(other.Data(), other.GetLength()));
  return *this;
 }
 CShString& Assign(const char* pStr)
 {
  Swap(CShString(pStr));
  return *this;
 }
 CShString& Assign(const char* pStr, int ilength)
 {
  Swap(CShString(pStr, ilength));
  return *this;
 }
 CShString& Append(const CShString& other)
 {
  int nSize = GetLength() + other.GetLength() + 1;
  char* pStr = new char[nSize];
  memcpy(pStr, Data(), GetLength());
  memcpy(pStr + GetLength(), other,Data(), other.GetLength() + 1);

  ResetAs(pStr, nSize);
 }
 CShString& Append(const char* pOther)
 {
  int nLen = strlen(pOther);
  int nSize = GetLength() + nLen + 1;
  char* pStr = new char[nSize];
  memcpy(pStr, Data(), GetLength());
  memcpy(pStr + GetLength(), pOther, nLen + 1);

  ResetAs(pStr, nSize);
 }
 CShString& Append(const char* pStr, int ilength)
 {
  int nSize = GetLength() + ilength + 1;
  char* pStr = new char[nSize];
  memcpy(pStr, Data(), GetLength());
  memcpy(pStr + GetLength(), pStr, ilength + 1);

  ResetAs(pStr, nSize);
 }
 ~CShString(void)
 {
  if (--*pn == 0)
  {
   delete pn;
   delete px;
  }
 }
 const char* Data() const
 {
  return px;
 }
 int GetLength()
 {
  return m_iLen;
 }
private:
 void ResetAs(char* pStr, int iSize)
 {
  if (--*pn == 0)
  {
   delete pn;
   delete px;
  }
  m_iMaxSize = CalcuMax(iSize);
  m_iLen = iSize - 1;
  px = pStr;
  pn = new int(1);
 }
 void Swap(CShString& other)
 {
  SwapFun(m_iLen, other.m_iLen);
  SwapFun(m_iMaxSize, other.m_iMaxSize);
  SwapFun(px, other.px);
  SwapFun(pn, other.pn);
 }
 static int CalcuMax(int iLen)
 {
  int i = 0;
  while (INIT_MAX_LEN + (i++) * DELTA_LEN < iLen + 1){}
  return INIT_MAX_LEN + (i - 1) * DELTA_LEN;
 }
 
 static const int INIT_MAX_LEN = 100;
 static const int DELTA_LEN = 20;
 int m_iLen;
 int m_iMaxSize;
 char* px;
 int* pn;
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值