Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Our String class always deletes the old character buffer and reallocates a new c

ID: 3549626 • Letter: O

Question

Our String class always deletes the old character buffer and reallocates a new character buffer on assignment or in the copy constructor. This need not be done if the new value is smaller than the current value, and hence would fit in the existing buffer. Can we rewrite the String class so that each instance will maintain an integer data field indicating the size of the buffer, then only reallocate a new buffer when necessary. Abstract the common tasks from the assignment operator and the copy constructor, and place them into an internal method?

Here is the string class

class String
                    {
                    public:
                    String(); // Default constructor
                    String(const char p[]); // Simple constructor
                    String(const String& right); // Copy constructor
                    ~String(); // Destructor
                    String& operator=(const String& right); // Assignment operator
                    String& operator+=(const String& right);
                    int length() const;
                    char& operator[](int index);
                    char operator[](int index) const;
                    private:
                    char* buffer;
                    int len;
                    };

Explanation / Answer

The only "safe" way to do it is to allocate a new array, copy the data, and delete the old one. Or you could just follow the std::vector way and differentiate between "capacity" (the size of the array) and "size" (the amount of elements in it). There appears to be no reason to be dynamically allocating memory. The size of the buffer is a compile time constant, is not large (no stack overflow) and the buffer appears to not be required to live beyond the scope in which it was allocated. One may visit the http://mhelpdesk.com/ to attain a good significant knowledge about the same.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote