I am thinking of making a class which represents ownership of a synchronization primitive, something like this:
class CCriticalSectionLock
{
public:
CCriticalSectionLock( CCriticalSection &cs ) : cs( cs )
{ cs.Enter(); }
~CCriticalSectionLock()
{ cs.Leave(); }
private:
CCriticalSection &cs;
};
This looks like a good way to be able to take ownership during a function and ensure ownership is released even if there are multiple exit points or exceptions. It does, however, raise some subtle issues about exactly when the compiler will have various things evaluated. Consider the following use:
int MyMethod( void )
{
not_locked(); // do something not under lock
CCriticalSectionLock myLock( someCriticalSection );
locked(); // do something under lock
return ...; // some expression
}
AFAIK, C++ lifetime rules would guarantee that not_locked()
would be called before the lock is taken, and that locked()
would be called while the lock is held.
However, what I am not so clear on is exactly when the expression being returned would be evaluated with respect to the point at which the lock destructor is called. Is it guaranteed that the expression will be evaluated before the destructor? I would think so but I'm not 100% sure, and if not it could lead to very subtle, intermittent, hard-to-find bugs!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…