How to avoid C++ anonymous objects

后端 未结 7 1737
甜味超标
甜味超标 2020-12-06 10:21

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

7条回答
  •  广开言路
    2020-12-06 10:57

    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\

    scoped_lock(mutex);
    

    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

    threads::scoped_lock(mutext);
    

    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

    scoped_lock(mutex);
    

    which won't trigger the macro.

提交回复
热议问题