c++ - c_str implemenation for String class -
i reading chapter 12 in accelerated c++ book on implementing string
class.
there end-of-chapter question implement c_str()
function. looking ideas.
here have far:
my first attempt heap allocate char *
, return it. result in memory leaks:
cost char * c_star() const { //cannot reference 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 attempt:
const char* c_str() const { //obviously incorrect implementation not nul('\0') terminated. return &data[0]; }
i cannot push_back '\0'
data since should not change data.
here spec:
returns pointer array contains null-terminated sequence of characters (i.e., c-string) representing current value of string object.
here book implementation: (renamed str
). internally, characters stored in vector implementation (vec).
class str { public: . . . private: vec<char> data; };
base on comments, implemented str class making sure there nul('\0') @ end of every string. instead of vector, store data in character array:
class str { public: typedef char* iterator; typedef const char* const_iterator; . . . //c_str return nul terminated char array const char* c_str() const { return str_beg; }; //c_str , data same implementation make sure there nul //at end const char* data() const { return str_beg; }; . . . private: iterator str_beg; . . . };
Comments
Post a Comment