I’m trying to use RAII to create objects which act on a stream until they’re destroyed. For example, I have a stream that flushes itself whenever endl is added. Most of the time I want this, but not always. I want to be able to say “don’t flush on endl” but I also need it to be exception safe. So I can’t just do stream->NoFlush() to set a class member. Anyway, what I’m wanting to know is this. If I have 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 lifetime of no_flush? For instance, it’s not used after line 2, but I need it to stay around until the end. I haven’t really heard of any optimizations like this, so I think I’m okay, but I’d like to make sure.
No, the compiler isn’t allowed to optimize that away. The destructor will be called exactly when the object goes out of scope.
What it could do is optimize copies of it if
NoFlushtakes the parameter by value, but that shouldn’t matter.Copy elision is the only optimization the compiler can perform that affects observable behavior.