为什么没有gcc / g ++警告未使用的临时? [英] Why is there no gcc/g++ warning for unused temporaries?

查看:165
本文介绍了为什么没有gcc / g ++警告未使用的临时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

void ListenerImpl::attach(boost::shared_ptr<ISubscriber> subscriber)
{
    boost::unique_lock<boost::mutex>(mtx);
    subscribers.push_back(subscriber);
}

void ListenerImpl::notify(MsgPtr msg)
{
    boost::unique_lock<boost::mutex>(mtx);

    //notify all subscribers
    BOOST_FOREACH(boost::shared_ptr<ISubscriber> subscriber, subscribers){
        subscriber->update(msg);
    }

}


这里的用户干预是保护attach()和notify()同时运行,因此boost :: unique_lock。
目标是保护订阅者容器。

但是确实很难注意到锁实际上只是临时(仔细看看,没有为它们分配名称)。
因此,当临时项被破坏时,互斥体上的锁将被立即释放,即代码不是线程安全的。
我会期望在这样的情况下编译器警告。类似未使用的临时。

But it is indeed extremely hard to notice that the locks are in fact just temporaries (take a closer look, there are no names assigned for them). So the lock on the mutex will be released immediately, when the temporary is destructed, i.e. the code is not thread safe. I would expect in situations like this a compiler warning. Something like "Unused temporary".

更糟糕的是,cppcheck也不会识别这个错误。
(cppcheck:ac / c ++代码分析工具 http:// sourceforge.net/apps/mediawiki/cppcheck/index.php?title=Main_Page

Even worse, cppcheck wouldn't recognize this mistake either. (cppcheck: a c/c++ code analysis tool http://sourceforge.net/apps/mediawiki/cppcheck/index.php?title=Main_Page)

Gcc对未使用的变量发出警告。临时这里是一个未使用的变量,肯定是程序员不注意的结果。
那么,为什么在这样的情况下没有警告?也许发现这种情况太复杂了?

Gcc issues warnings on unused variables. The temporary here is an unused variable, and definitely the result of the programmer's inattention. So, why there are no warnings in cases like this? Maybe it is too complicated to discover such situations?

推荐答案

编译器不发出警告,因为很可能更新构造函数中的一些 static-member / global 变量(这是有效和有意义的)。例如:

Compiler doesn't issue a warning, because it's quite possible that you might be updating some static-member / global variable inside the constructor (which is valid and meaningful). e.g.:

struct A
{
  static int count;
  A () { count ++; }
};

现在当你简单地调用一个临时:

Now when you simply invoke a temporary:

A();

如果这样的更新没有发生,编译器不会挖入 A ,并检查是否有用。它总是假定是一个有效的场景。有很多这样的情况可以指出与临时相关。

In case if such update is not happening, compiler will not dig into the constructor of A and check if something useful is happening. It always assumes to be a valid scenario. There are many such cases can be pointed out related to temporaries.

这篇关于为什么没有gcc / g ++警告未使用的临时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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