Thread: Writing my own string class.

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Sep 2004
    Posts
    80

    Writing my own string class.

    I have a few questions about C-style strings. If I wanna change the string contained in my class as it is now I must make the pointer data point to another C-style string, but if I do this alot there will be plenty of static strings in memory. The problem with this is that, if I one day decide to make a chat program (or any other program in need of input) and my string keeps pointing to new data everytime I input something there will be a hugh waste of memory, wont it? I know about dynamic memory allocation using malloc/free or new/delete but still I will never know exactly how much input the program might receive.

    Other situations I will have the same trouble is if I want to concatenate two strings or copy strings, then I will have to set dato to point elsewhere but the old information will still be in memory.

    What I really want to know is if there is a good way to save memory in this case? My very unfinished string class looks as follows:
    Code:
    class Str
    {
        private:
    
        char* data;
        int length;
    
        void set(char* text)
        {
            data = text;
            length = getlen();
        }
    
        int getlen()
        {
            if (data == NULL)
                return 0;
    
            int i = 0;
    
            while (*data++ != '\0')
                i++;
    
            return i;
        }
    
        public:
    
        Str()
        {
            data = NULL;
            length = 0;
        }
    
        Str(char* text)
        {
            set(text);
        }
    
        void operator=(char* text)
        {
            set(text);
        }
    
        int len()
        {
            return length;
        }
    };
    Last edited by antex; 10-27-2006 at 07:05 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C++ ini file reader problems
    By guitarist809 in forum C++ Programming
    Replies: 7
    Last Post: 09-04-2008, 06:02 AM
  2. Custom String class gives problem with another prog.
    By I BLcK I in forum C++ Programming
    Replies: 1
    Last Post: 12-18-2006, 03:40 AM
  3. Message class ** Need help befor 12am tonight**
    By TransformedBG in forum C++ Programming
    Replies: 1
    Last Post: 11-29-2006, 11:03 PM
  4. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM