I am trying to use RAII to create objects that act on a thread until they are destroyed. For example, I have a thread that is reset every time endl added. Most of the time I want this, but not always. I want to say "not flush on endl", but I also need it to be safe for exceptions. Therefore, I cannot just do stream->NoFlush() to set the class member. Anyway, I want to know this. If I have a code like
CStreamModifier no_flush; stream->NoFlush(no_flush); // as long as no_flush is in scope I get the behaviour I want ... do some stuff on the stream, without referencing no_flush ... // no_flush goes out of scope here.
Is the compiler allowed to optimize the no_flush lifetime? For example, it is not used after line 2, but I need it to stay until the end. I really have not heard of optimizations like this, so I think I'm fine, but I would like to make sure.
source share