如何避免 C++ 匿名对象

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

问题描述

我有一个 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++ 匿名对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)