Optimization/clarity coding : what is gcc able to do for me ?

Nick NoSpam nicknospam@optonline.net
Sat Jan 15 21:08:00 GMT 2005


On Sat, 2005-01-15 at 14:36 +0100, jlh wrote:
> Nick NoSpam wrote:
> > 2.  Can the compiler optimize the size() call away (after calling it
> > once)?  What if the vector was accessible in another thread?  The other
> > thread could modify the vector simultaneously.
> 
> That code wouldn't be thread-safe.  If two threads need to access the same
> vector, you'd have to use a mutex, or bad things could happen.
Actually, that code may or may not be thread-safe--it depends on the STL
implementation.  Most STL implementations are thread safe if only one
thread is modifying at any time, and any number of threads are reading
at the same time.  So since one thread is reading (size() is a const
method), and another may be writing (perhaps adding new elements), it's
fine for such implementations.

But that's not the point.  The compiler can't optimize away a function
call if it doesn't know if the return value (or side effects) will be
the same, right?


Regards,
Nick G



More information about the Gcc mailing list