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!

有帮助吗?

解决方案

If they weren't, that would be very problematic.

Indeed, consider the following code :

int function(){

    MyClass myObject;
    //stuff
    return 5 + myObject.getNumericalValue();
}

with getNumericalValue() a simple member function that returns an int based on computations on member variable. If the expression was evaluated after the destruction of myObject, you would have undefined behavior, and using locals would be impossible in return statement (which isn't the case).

In your case, the lock will be destroyed after the evaluation of the return statement.

To add some strictness to that, let me quote the standard (§3.7.3/3, emphasis mine) :

If a variable with automatic storage duration has initialization or a destructor with side effects, it shall not be destroyed before the end of its block, nor shall it be eliminated as an optimization even if it appears to be unused

The end of the block, for a function, is after the return statement.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top