如何避免C ++匿名对象 [英] How to avoid C++ anonymous objects

查看:123
本文介绍了如何避免C ++匿名对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ScopedLock 类,它可以帮助在超出范围时自动释放锁。
然而,问题是:有时团队成员会写出无效的锁码,如

  {
ScopedLock (互斥); // anonymous
xxx;



$ b上面的代码是错误的,因为 ScopedLock
code> object被构造并立即被破坏 ,所以它无法锁定预期区域( xxx )。我希望编译器在尝试编译此类代码时发生错误。可以这样做吗?



我已经搜寻过 g ++ 警告选项,但未能找到正确的选项。

b
$ b

  #define LOCK(mutex)ScopedLock _lock(mutex)

然后像这样使用它:

  {
LOCK(mutex);
xxx;





$ b

另外,Java的 synchronize block可以使用一个宏构造来模拟:在for循环中总是只运行一次,我在for循环的初始化语句中实例化了一个这样的locker,所以它在离开for-loop时会被销毁。



然而,它有一些缺陷,一个 break 语句的意外行为就是一个例子。这个黑客是介绍这里






当然,上述方法都不能完全避免像您​​的示例那样的意外代码。但是,如果您习惯使用两个宏中的一个来编写锁定互斥锁,它将不太可能发生。因为除了宏定义,locker类的名称将永远不会出现在代码中,所以甚至可以在版本控制系统中引入一个提交挂钩,以避免提交无效代码。


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;
}

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.

解决方案

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:

{
    LOCK(mutex);
    xxx;
}


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.

这篇关于如何避免C ++匿名对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆