简体   繁体   中英

c_str implemenation for String class

I am reading chapter 12 in the Accelerated C++ book on implementing string class.

There is a end-of-chapter question to implement the c_str() function. I am looking for some ideas.

Here is what I have so far:

My first attempt was to heap allocate a char * and return it. But that would result in memory leaks:

cost char * c_star() const {
   //cannot get reference to result later
   //causes memory leaks

   char* result = new char[data.size() + 1];
   std::copy(data.begin(), data.end(), result);
   result[data.size()] = '\0';
   return result;
}

Here is another attempt:

const char* c_str() const {
    //obviously incorrect implementation as it is not NUL('\0') terminated.
    return &data[0];
}

I cannot push_back '\\0' to data since it should not change the data.

Here is the spec :

Returns a pointer to an array that contains a null-terminated sequence of characters (ie, a C-string) representing the current value of the string object.

Here is book implementation: (Renamed to Str ). Internally, the characters are stored in a vector implementation (Vec).

class Str {
    public:
       .
       .
       .

    private:
        Vec<char> data;
};

Base on the comments, I implemented the Str class be making sure there is a NUL('\\0') at the end of every string. Instead of vector, I store data in a character array:

class Str {
    public:
        typedef char* iterator;
        typedef const char* const_iterator;
        .
        .
        .
        //c_str return a NUL terminated char array
        const char* c_str() const { return str_beg; };
        //c_str and data are same as implementation make sure there is NUL
        //at the end
        const char* data() const { return str_beg; };
        .
        .
        .

    private:
        iterator str_beg;
        .
        .
        .
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM