dimanche 6 décembre 2015

Implementation of cstring wrapper class

I want to have a thin wrapper (low overhead) around c-style string. Also, with some additional features like equals and lt operators for map indexing. I have come up with the following class.

Can somebody comment on it?

From what I've gathered this class would take only as much memory as pointer, so much less than std::string.

inline char * dupStr(const char * s){
    if(!s){return nullptr;}
    char * d = new char[strlen(s)+1];
    strcpy(d,s);
    return d;
}



class CString_{
    private:
        const char *s_;

    public:
        CString_(const char *s):s_(dupStr(s)){}
        CString_(const std::string &s):CString_(s.c_str()){}
        CString_(const CString_ &that):s_(dupStr(that.s_)){}
        CString_(CString_ &&that):s_(that.s_){
            that.s_ = nullptr;
        }

        CString_ & operator= (const CString_ & that) = delete;
        CString_ & operator= (CString_ && that) = delete;

        ~CString_(){ delete[] s_;}

        const char * get() const {return s_;}

        bool operator<(const CString_ &that) const{
            return strcmp(s_,that.s_) < 0;
        }

        bool operator==(const CString_ &that) const{
            return strcmp(s_,that.s_) == 0;
        }
};

Aucun commentaire:

Enregistrer un commentaire