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