用于写入文件的 stringstream 或 ostringstream?

stringstream or ostringstream for writing in file?

要将数据从 ostringstream 写入 ofstream,我必须这样写:

std::ostringstream ss;
myFile<<ss.str();

另一方面,如果我使用 stringstream 我可以直接访问缓冲区:

std::stringstream ss;
myFile<<ss.rdbuf();

问题是 ostringstream::str() 复制了一个有点糟糕的字符串,因为在我的程序中有非常大的字符串,所以 stringstream 应该更好,因为我可以直接访问读取缓冲区。这里的人说如果我们只处理输出操作,我们应该使用 ostringstream 而不是 stringstream。我不能简单地使用字符串,因为我要插入各种类型的数据。那么有人可以就如何处理这个问题给我建议吗?

people here say that we should use ostringstream over the stringstream if we deal only with output operations

使用更具体的 ostringstream 的主要原因是为了明确您的意图并避免错误。在这种情况下,需要 stringstream 来防止复制可能很大的字符串,因此请谨慎使用它。

ostringstream 适用于数据进入流而永远不会出来的情况。 (当然,您真正想要的 std::string 对象除外。)

stringstream 适用于读写同时发生的情况。 << rdbuf() 是一种从流中读取的方式,所以 stringstream 是完全合适的。