[英]c_str implemenation for String class
我正在閱讀Accelerated C ++書中有關實現string
類的第12章。
有一個實現c_str()
函數的章尾問題。 我正在尋找一些想法。
這是我到目前為止的內容:
我的第一個嘗試是堆分配 char *
並返回它。 但這會導致內存泄漏:
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;
};
基於這些注釋,我實現了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;
.
.
.
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.