学习笔记:CString封装

#include "stdafx.h"
#include <iostream>
#include <string>
#include <boost/algorithm/string/trim.hpp>
#include <boost/array.hpp>

class String
{
    enum { STATIC_SIZE=30 };
        
    std::string& str() { return reinterpret_cast<std::string&>(*a_); }
    const std::string& str() const { return reinterpret_cast<const std::string&>(*a_); }

public:

    template <int N>
    String& Manipulate();
 

    String(){ 
        zero(); 
    }

    String(const char* s){ 
        zero(); set_buff(s); 
    }

    String(const String& rhs){  
        zero(); set_buff(rhs.c_str());
    }

    ~String() throw(){ 
        if (f_) reinterpret_cast<std::string*>(a_)->~basic_string();
    }

    String& operator=(const String& rhs){
        set_buff(rhs.c_str());
        return *this;
    }

    size_t size() const
    {
        if (f_) return str().size();
        return strlen(a_);
    }

    const char* c_str() const{
        if (f_){
            return str().c_str();
        }
        else{
            return a_;
        }
    }

    friend std::ostream& operator<<(std::ostream& os, String& s){
        if (s.f_){
            os << s.str();
        }
        else{
            os << s.a_;
        }
        return os;
    }

private:  
    
    //初始化为空字符串
    void zero(){
        f_=0;
        a_[0]=0;
    }

    //存入字符串
    void set_buff(const char* s){

        //已经升级为std::string了
        if (f_){
            str() = s;
        }
        else{
            //字符串太长,应用std::string
            if (strlen(s)>STATIC_SIZE){
                new (a_) std::string(s);
                f_=1;
            }
            else{
                strcpy(a_,s);
            }
        }
    }

    //静态数组。当字符串比较小时,就直接存在这里。
    //否则在这个数组上,placement new一个std::string
    char a_[STATIC_SIZE+1];            
    char f_; //指示存储类型,动态 1 静态 0  

};


//特化版本可以直接访问String的私有成员
template <>
String& String::Manipulate<1>(){
    if (f_){
        boost::algorithm::trim(str());
    }
    else{
        std::string t = a_;
        boost::algorithm::trim(t);
        set_buff(t.c_str());
    }
    return *this;
}
//trim函数的简便写法
#define trim String::Manipulate<1> 


int main()
{
    
    for (int i=0;i<10000000;++i){
        String s("123456789");
        const char* str = s.c_str();
    }

    system("pause");

    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值