Reputation: 1614
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 (i.e., 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;
};
Upvotes: 1
Views: 468
Reputation: 1614
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;
.
.
.
};
Upvotes: 2