1

我需要在 C++ 中的“char *”中存储一定数量的数据,因为我想避免 std::string 在超过 max_size() 时耗尽内存。但是数据来自网络的数据块,所以我每次获取数据块时都需要使用重新分配。C++ 中的 char * 重新分配和连接有什么优雅的解决方案吗?

4

3 回答 3

3

在 Visual Studio 中,max_size() 是 4294967294 个字符,大约 4Gb。如果你能告诉我们你是如何冒着超过这么多字符的风险的,那将会很有趣。

如果问题不经常出现,而这只是为了使其故障安全,那么

 myConcatStr(string str1, string str2)
 {
      if (str1.length() + str2.length()) <= str1.max_size() // if there is no overflow problem
           str1.append(str2); // use stl append
      else
           //use alternate method instead or throw an exception
 }
于 2010-04-29T08:19:50.407 回答
2

您可以采用 C 方式并使用malloc()/ realloc(),但realloc()只会分配一个新块,将旧内容复制到新内容中,并且有时无论如何都会释放旧块。也很难正确使用。

您可以分配一个巨大的缓冲区和/或以指数方式增长它,从而抵消问题的严重性。

或者你可以使用绳索

于 2010-04-29T04:34:17.327 回答
1

随着字符串大小的增长,我们想到了 std:vector 进行自动分配。只需将 aVector<char>和 push_back() 字符分配给您的内容即可。

于 2010-04-29T04:35:02.397 回答