C++ fixed length string class?

前端 未结 10 1087
遇见更好的自我
遇见更好的自我 2020-12-17 17:56

Is there anything like this in Standard C++ / STL? Ideally it should be constructed like

fstring s = fstring(10);

I need to sometimes cons

10条回答
  •  一整个雨季
    2020-12-17 18:28

    I've been using something like this for strings allocated on stack or as a part of another object. Which in release becomes a char*

    #ifdef DEBUG
    #define STR_DEBUG
    #endif
    
    #define FIXED_STRING( maxSize ) ReservedString _Tmp##__LINE__; 
    
    class FixedString{
    public:
        FixedString& operator =( char const * const pStr );
        //FixedString& operator =( FixedString const &pStr );
        operator const char*() const { return mStr; }
        const char* cStr() const { return mStr; }
        FixedString& operator +=(const char *pStr);
        bool equals( const char *pStr );
        bool beginsWith( const char *pStr );
        /// rises ASSERT if not enough
        void ensureEnoughForNMore( int NMoreSymbols );
    protected:
        char *mStr;
        #ifdef STR_DEBUG
            ui16 mMaxLength;
        #endif
    
    private:
        #ifdef STR_DEBUG
            FixedString( char *str, ui16 maxLength ): mStr(str), mMaxLength(maxLength) {}
        #else
            FixedString( char *str ): mStr(str) {}
        #endif
        template
        friend  class ReservedString;
    };
    
    template  class ReservedString{
    public:
        operator FixedString() { 
            #ifdef STR_DEBUG
                return FixedString( mBuf, MAX_LENGTH );
            #else
                return FixedString( mBuf );
            #endif
        }   
    private:
        char mBuf[MAX_LENGTH+1];
    };
    

提交回复
热议问题