1

我正在阅读Accelerated C++ book 关于实现string类的第 12 章。

有一个章末问题来实现该c_str()功能。我正在寻找一些想法。

这是我到目前为止所拥有的:

我的第一次尝试是堆分配achar *并返回它。但这会导致内存泄漏:

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;
}

这是另一个尝试:

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

我不能push_back '\0'数据,因为它不应该改变数据。

这是规格

返回一个指向数组的指针,该数组包含一个以空字符结尾的字符序列(即一个 C 字符串),表示字符串对象的当前值。

这是本书的实现:(重命名为Str)。在内部,字符存储在矢量实现 (Vec) 中。

class Str {
    public:
       .
       .
       .

    private:
        Vec<char> data;
};
4

1 回答 1

2

根据评论,我实现了 Str 类以确保每个字符串的末尾都有一个 NUL('\0') 。我将数据存储在字符数组中,而不是向量:

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;
        .
        .
        .
};
于 2016-01-20T20:09:29.500 回答