std :: stringrink_to_fit损坏字符串

因此,我有一个std::string对象,该对象由C样式的函数填充,例如strcpy。该函数可以返回10-100个字符之间的任意位置,因此我在字符串中保留了100个字符。

但是使用&buf[0]可行,但是当我尝试shrink_to_fit()时,字符串被破坏了。如何避免这种情况?

std::string buf;
buf.reserve(100);
//example of the function that can write to a buffer with 10-100 characters.
strcpy(&buf[0],"Hello");
buf.shrink_to_fit();
std::cout << buf << std::endl;
suzhuang 回答:std :: stringrink_to_fit损坏字符串

reserve()设置字符串的容量,而不是其大小。两件事。 capacity 是已分配多少内存来容纳字符。 size 是分配的内存中实际上有多少个字符有效。

shrink_to_fit()缩小容量以匹配当前的 size 。但是您字符串的 size 始终为0,因此无论您是否调用shrink_to_fit(),该字符串实际上都是空的,没有损坏。打印std::string会打印字符直至其大小,而不是其容量

您需要使用resize()而不是reserve(),例如:

std::string buf;
buf.resize(100);
//example of the function that can write to a buffer with 10-100 characters.
strcpy(&buf[0],"Hello");
buf.resize(strlen(buf.c_str()));
buf.shrink_to_fit();
std::cout << buf << std::endl;

话虽这么说,{shrink_to_fit(),例如:

std::string

或者,在C ++ 17和更高版本中,您可以改用std::array<char,100> buf; //example of the function that can write to a buffer with 10-100 characters. strcpy(buf.data(),"Hello"); std::string str(buf.data(),strlen(buf.data())); std::cout << str << std::endl; ,例如:

std::string_view
本文链接:https://www.f2er.com/3156666.html

大家都在问