c++ - Filling a std string with memcpy does not set length -
i have following code fill std::string
curl response.
struct curl_string { std::string tmpstr; size_t len; }; void init_string(struct curl_string *s) { s->len = 0; } size_t writefunc(void *ptr, size_t size, size_t nmemb, struct curl_string *s) { size_t new_len = s->len + size*nmemb; s->tmpstr.reserve(new_len + 1); memcpy(&s->tmpstr[0] + s->len, ptr, size*nmemb); s->tmpstr[new_len] = '\0'; s->len = new_len; return size*nmemb; }
the problem is, though reserve correct length, when try read string, size still 0.
i wanted avoid using loop add 1 character @ time. there way still have correct string length in std::string
?
your problem std::string::reserve
reserves memory characters, doesn't alter length of string. size isn't recalculated when underlying buffer modified, because near-impossible detect in cases.
the solution use resize
instead of reserve
:
s->tmpstr.resize(new_len + 1);
is there reason keeping track of length manually? can call s->tmpstr.size()
.
Comments
Post a Comment