哪个更有效/更简洁:清除现有字符串流或创建新字符串流?

发布于 2024-12-25 00:02:37 字数 589 浏览 1 评论 0原文

简单的问题只是出于好奇。

一个类上的多个方法需要使用 stringstream,或者特别是 ostringstream。

1) 将 stringstream 变量作为类成员,然后在使用它之前清除它,即 msg.str("")

2) 创建每次需要使用它时,都会在每个方法中本地创建一个新的 stringstream 变量。

就效率和整洁而言,哪种是实现此目的的最佳方法?

我的预感是选项 1,但不确定初始构造与每次调用 str() 相结合是否会更糟?

PS我读过 初始化..哪个更高效? 和 < a href="https://stackoverflow.com/questions/6030339/which-is-quicker-more-efficient">哪个更快/更高效?,我的下一步是研究分析并编写一个小型测试应用程序,但我觉得询问可能会更快:-)

Simple question just out of curiosity.

Multiple methods on a class need to use a stringstream, or specifically an ostringstream.

1) Have a stringstream variable as a class member and then just clear it before using it i.e. msg.str("")

2) Create a new stringstream variable locally in each method each time you need to use it.

Which is the best way of implementing this, in terms of efficiency and neatness?

My hunch is option 1, but not sure if the initial construction combined with each call to str() would be worse?

P.S. I've read Initializing.. which one is more efficient? and Which is quicker/more efficient?, my next step would be for me to look into profiling and writing a small test app, but I felt asking might be quicker :-)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

埖埖迣鎅 2025-01-01 00:02:37

一开始就不要使用stringstream。使用 istringstream
ostringstream,无论哪个都合适。并且只能使用一次;
清除它是一个复杂的操作,需要好几行代码,
而且很容易忘记一些事情。 msg.str("") 没有开始
解决所有国家的问题。您还需要重置格式标志,
错误状态、异常掩码和任何其他格式
通过 xalloc 获取的变量中设置的信息。

Don't use stringstream to begin with. Use either istringstream or
ostringstream, which ever is appropriate. And only use it once;
clearing it is a complex operations, requiring several lines of code,
and it is easy to forget something. msg.str("") doesn't begin to
address all of the state. You also need to reset the formatting flags,
the error status, the exception mask, and any additional formatting
information set in variables acquired by means of xalloc.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文