哪个更有效/更简洁:清除现有字符串流或创建新字符串流?
简单的问题只是出于好奇。
一个类上的多个方法需要使用 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一开始就不要使用
stringstream
。使用istringstream
或ostringstream
,无论哪个都合适。并且只能使用一次;清除它是一个复杂的操作,需要好几行代码,
而且很容易忘记一些事情。
msg.str("")
没有开始解决所有国家的问题。您还需要重置格式标志,
错误状态、异常掩码和任何其他格式
通过 xalloc 获取的变量中设置的信息。
Don't use
stringstream
to begin with. Use eitheristringstream
orostringstream
, 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 toaddress 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
.