Raymond Raymond - 3 days ago 5
C++ Question

How to avoid C++ anonymous objects

I have a

class which can help to release lock automatically when running out of scope.
However, the problem is: Sometimes team members write invalid lock-code such as

ScopedLock(mutex); // anonymous

The above code is wrong because the
object is constructed and destructed immediately, so it fails to lock the expected area (
). I want the compiler to give an error when trying to compile such code. Can this be done?

I have searched
warning options, but fail to find the right one.


To avoid this, introduce a macro which does this for you, always using the same name for the locker:

#define LOCK(mutex) ScopedLock _lock(mutex)

Then use it like this:


As an alternative, Java's synchronize block can be simulated using a macro construct: In a for-loop running always exactly once, I instantiate such a locker in the initialization statement of the for-loop, so it gets destroyed when leaving the for-loop.

However, it has some pitfalls, unexpected behavior of a break statement being one example. This "hack" is introduced here.

Of course, none of the above methods fully avoid accidental code like your example. But if you're used to write locking mutexes using one of the two macros, it will less likely happen. As the name of the locker class will then never appear in the code except in the macro definition, you can even introduce a commit hook in a version control system to avoid committing invalid code.