Life optimization of a C ++ object

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.

+4
source share
2 answers

No, the compiler cannot optimize this. The destructor will be called exactly when the object goes out of scope.

What he can do is optimize his copies if NoFlush accepts a parameter by value, but that doesn't matter.

Copying elision is the only optimization a compiler can do that affects observable behavior.

+2
source

I would do it like this:

 struct Stream { bool flush = true; // ... }; struct NoFlush { explicit NoFlush(Stream & s) : stream(s) , prev(stream.flush) { stream.flush = false; } ~NoFlush() { stream.flush = prev; } Stream & stream; bool prev; }; 

Now you can use it as follows:

 void foo(T arg, S brg, Stream & stream) { NoFlush _(stream); // do stuff } 
+2
source

All Articles