namespace - front class in c++

How to avoid C++ anonymous objects (4)

I have a ScopedLock 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 ScopedLock object is constructed and destructed immediately, so it fails to lock the expected area (xxx). I want the compiler to give an error when trying to compile such code. Can this be done?

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

AFAIK there's no such a flag in gcc. A static analyzer may better suit your needs.

I have seen an interesting trick in one codebase, but it only works if your scoped_lock type is not a template (std::scoped_lock is).

#define scoped_lock(x) static_assert(false, "you forgot the variable name")

If you use the class correctly, you have

scoped_lock lock(mutex);

and since the scoped_lock identifier isn't followed by an open paren, the macro won't trigger and the code will remain as it is. If you write\


the macro will trigger and the code will be substituted with

static_assert(false, "you forgot the variable name");

This will generate an informative message.

If you use a qualified name


then the result will still not compile, but the message won't be as nice.

Of course, if your lock is a template, the bad code is


which won't trigger the macro.

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.

You can use a class and deleted function with the same name. Unfortunately this requires adding "class" keyword before the type.

class Guard
  explicit Guard(void)

static void Guard(void) = delete;

int main()
  // Guard(); // Won't compile
  // Guard g; // Won't compile
  class Guard g;