std :: stringrink_to_fit损坏字符串

Aru*_*pur -1 c++ string buffer stl

因此,我有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;
Run Code Online (Sandbox Code Playgroud)

Rem*_*eau 7

reserve()设置字符串的容量,而不是大小。两件事。该容量是多少内存已分配给持有字符。该尺寸是分配的内存里面很多人物是如何真正有效。

shrink_to_fit()缩小容量以匹配当前大小。但是您的字符串大小始终为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;
Run Code Online (Sandbox Code Playgroud)

话虽这么说,shrink_to_fit()并不需要做任何事情,它是实现定义。您可能会考虑使用单独的缓冲区来读取字符,然后std::string从该缓冲区构造字符,例如:

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;
Run Code Online (Sandbox Code Playgroud)

或者,在C ++ 17和更高版本中,您可以改用std::string_view例如:

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_view sv(buf.data(), strlen(buf.data()));
std::cout << sv << std::endl;
Run Code Online (Sandbox Code Playgroud)