std::string shrink_to_fit 损坏字符串
std::string shrink_to_fit corrupts string
所以我有这个 std::string
对象,它由 C 风格函数填充,例如 strcpy
。该函数可以 return 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;
reserve()
设置字符串的 容量 ,而不是 大小 。两种不同的东西。 容量 是分配给字符的内存量。 size 是分配的内存中实际有效的字符数。
shrink_to_fit()
缩小 容量 以匹配当前 大小 。但是您的字符串的 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
,例如:
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;
或者,在 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;
所以我有这个 std::string
对象,它由 C 风格函数填充,例如 strcpy
。该函数可以 return 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;
reserve()
设置字符串的 容量 ,而不是 大小 。两种不同的东西。 容量 是分配给字符的内存量。 size 是分配的内存中实际有效的字符数。
shrink_to_fit()
缩小 容量 以匹配当前 大小 。但是您的字符串的 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
,例如:
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;
或者,在 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;