6

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 :-)

Community
  • 1
  • 1
Adam Marshall
  • 3,010
  • 9
  • 42
  • 80
  • The problem with asking is that the answers will be full of religion and folklore and most likely will not apply to your situation. Profiling should be preferred. – PlasmaHH Jan 06 '12 at 10:47
  • @PlasmaHH: profiling only shows performance... if done right. Asking may also point to other flaws in some of the approaches (related to the "neat" aspect for example). That said, I can only agree that subjectivity is a risk. – Matthieu M. Jan 06 '12 at 10:55
  • And the problem with profiling is it answers the question for the environment you're running in (if you don't stuff it up - profiling can be tricky to do right), and you don't learn about consistency, portability or correctness issues like James pointed out.... – Tony Delroy Jan 06 '12 at 10:55
  • @MatthieuM.: I would argue that "neatness" is equally subjective, but my answer mostly was targetting the efficiency aspect of this question. – PlasmaHH Jan 06 '12 at 11:12

1 Answers1

8

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.

James Kanze
  • 150,581
  • 18
  • 184
  • 329