0

I am using an ostringstream object in an application that runs for a long time to print debug information to standard out. I toggle whether the application actually prints and clears the ostringstream object based on a command line arg (e.g., verbose flag). When the verbose switch is not asserted I still write to the ostringstream object but I never clear it.

I am trying to figure out how bad this is and whether I should take more care on clearing the object? Are there any negative repercussions such as using too much memory?

// example code 
ostringstream oss;
while (1){
    oss << " still alive " << endl;
    if (verbose) { cout << oss.str(); oss.str("") } 
}
BigBrownBear00
  • 1,378
  • 2
  • 14
  • 24
  • Well, if you never empty it, eventually you will consume all your memory. – NathanOliver May 01 '17 at 13:23
  • How are we supposed to know if you are using too much memory? – Christian Hackl May 01 '17 at 13:24
  • It might be a better solution to set up the output stream once depending on the command line flag and then just always write unconditionally to that stream. – Kerrek SB May 01 '17 at 13:25
  • @KerrekSB I didn't do that b/c I wanted to avoid a lot of conditional tests in sections of code that contain a lot of loops – BigBrownBear00 May 01 '17 at 13:33
  • It's probably a bit counterproductive to be worrying about the performance of conditionals while using streaming I/O. Consider implementing a [no-op stream](http://stackoverflow.com/q/11826554/501250) and conditionally assigning `oss` from either `std::cout` or the dummy stream depending on whether `verbose` is set. And don't use `endl` unless you need the output flushed. – cdhowie May 01 '17 at 13:46

1 Answers1

1

Obviously when you keep inserting data in the stream it'll consume more memory, which at some point can be a lot.

Clearing it will prevent that.

deW1
  • 5,562
  • 10
  • 38
  • 54