问题描述
我有一个 ScopedLock
类,它可以帮助在超出范围时自动释放锁.但是,问题是:有时团队成员会编写无效的锁定代码,例如
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
xxx;
}
上面的代码是错误的,因为ScopedLock
对象是立即构造和销毁的,所以没能锁定预期的区域(xxx
).我希望编译器在尝试编译此类代码时给出错误.这个可以吗?
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?
我已经搜索了 g++
警告选项,但没有找到正确的选项.
I have searched g++
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)
然后像这样使用它:
{
LOCK(mutex);
xxx;
}
<小时>
作为替代方案,Java 的 synchronize
块可以使用宏构造来模拟:在始终只运行一次的 for 循环中,我在 for 循环的初始化语句中实例化了这样一个锁,所以离开for循环时它会被破坏.
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.
然而,它有一些陷阱,break
语句的意外行为就是一个例子.这个hack"介绍 这里.
However, it has some pitfalls, unexpected behavior of a break
statement being one example. This "hack" is introduced here.
当然,上述方法都不能完全避免像您的示例那样的意外代码.但是,如果您习惯于使用这两个宏之一来编写锁定互斥锁,就不太可能发生这种情况.由于 locker 类的名称将永远不会出现在代码中,除非在宏定义中,您甚至可以在版本控制系统中引入提交挂钩以避免提交无效代码.
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.
这篇关于如何避免 C++ 匿名对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!