有一段时间,一位同事告诉我,他花了很多时间来调试竞争条件.罪魁祸首竟然是这样的:
void foo()
{
ScopedLock(this->mutex); // Oops, should have been a named object.
// Edit: added the "this->" to fix compilation issue.
// ....
}
Run Code Online (Sandbox Code Playgroud)
为了防止情况再次发生,他在定义ScopedLock类之后创建了以下宏:
#define ScopedLock(...) Error_You_should_create_a_named_object;
Run Code Online (Sandbox Code Playgroud)
这个补丁工作正常.
有没有人知道任何其他有趣的技术来防止这个问题?
您应该使用静态代码分析器,例如Cppcheck.对于以下代码:
class a { };
void f() {
a();
}
Run Code Online (Sandbox Code Playgroud)
cppcheck生成以下输出:
$ cppcheck test.cpp
Checking test.cpp...
[test.cpp:4]: (error) instance of "a" object destroyed immediately
Run Code Online (Sandbox Code Playgroud)
还检测到各种其他常见编码错误.
(我是Cppcheck的一个相当新的贡献者.几个月前我发现了它,并且使用它很棒.)
如果你要定义一个宏,我可能宁愿定义这个:
#define GET_SCOPED_LOCK(name, mtx) ScopedLock name(mtx)
Run Code Online (Sandbox Code Playgroud)
并停止通过宏以外的方式创建对象。
然后重命名ScopedLock为ThisClassNameShouldNotAppearInUserCode如果有帮助的话。