关于RAII:如何防止由意外创建临时错误导致的错误? [英] Concerning RAII: How to prevent errors caused by accidentally creating a temporary?
问题描述
同年龄的同事告诉我,他花了很多时间调试一个竞争条件。犯罪分子原来是这样的:
A while age a colleague told me he spent lot of time debugging a race condition. The culprit turned out to be something like this:
void foo()
{
ScopedLock(this->mutex); // Oops, should have been a named object.
// Edit: added the "this->" to fix compilation issue.
// ....
}
再次发生,他在ScopedLock类的定义之后创建了以下宏:
In order to prevent situation from happening again he created the following macro after the definition of the ScopedLock class:
#define ScopedLock(...) Error_You_should_create_a_named_object;
这个补丁很好用。
任何人都知道任何其他有趣的技术来防止这个问题?
Does anyone know any other interesting techniques to prevent this problem?
推荐答案
如果你要定义一个宏,而不是定义这个:
If you're going to define a macro, I'd probably rather define this one:
#define GET_SCOPED_LOCK(name, mtx) ScopedLock name(mtx)
并停止通过宏创建对象。
and stop creating objects other than via the macro.
然后重命名 ScopedLock
到 ThisClassNameShouldNotAppearInUserCode
如果这有帮助。
Then rename ScopedLock
to ThisClassNameShouldNotAppearInUserCode
if that helps.
这篇关于关于RAII:如何防止由意外创建临时错误导致的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!