c_str 字符串 class 的实现
c_str implemenation for String class
我正在阅读 Accelerated C++ 书中关于实施 string
class 的第 12 章。
有一个章末问题来实现 c_str()
功能。我正在寻找一些想法。
这是我目前的情况:
我的第一次尝试是堆分配一个char *
和return它。但这会导致内存泄漏:
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()] = '[=12=]';
return result;
}
这是另一个尝试:
const char* c_str() const {
//obviously incorrect implementation as it is not NUL('[=13=]') terminated.
return &data[0];
}
我不能 push_back '[=18=]'
数据,因为它不应该改变数据。
这里是spec:
Returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.
这是本书的实现:(重命名为 Str
)。在内部,字符存储在向量实现 (Vec) 中。
class Str {
public:
.
.
.
private:
Vec<char> data;
};
根据评论,我实现了 Str class 以确保每个字符串的末尾都有一个 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;
.
.
.
};
我正在阅读 Accelerated C++ 书中关于实施 string
class 的第 12 章。
有一个章末问题来实现 c_str()
功能。我正在寻找一些想法。
这是我目前的情况:
我的第一次尝试是堆分配一个char *
和return它。但这会导致内存泄漏:
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()] = '[=12=]';
return result;
}
这是另一个尝试:
const char* c_str() const {
//obviously incorrect implementation as it is not NUL('[=13=]') terminated.
return &data[0];
}
我不能 push_back '[=18=]'
数据,因为它不应该改变数据。
这里是spec:
Returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.
这是本书的实现:(重命名为 Str
)。在内部,字符存储在向量实现 (Vec) 中。
class Str {
public:
.
.
.
private:
Vec<char> data;
};
根据评论,我实现了 Str class 以确保每个字符串的末尾都有一个 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;
.
.
.
};