Why is there no gcc/g++ warning for unused temporaries?

前端 未结 3 793
感情败类
感情败类 2020-12-17 18:17

Consider the following code :

void ListenerImpl::attach(boost::shared_ptr subscriber)
{
    boost::unique_lock(mtx);
          


        
相关标签:
3条回答
  • 2020-12-17 19:00

    hmm.. I am not sure but can't this be protected against with normal c++ also?

    class Mutex;
    class Lock {
        Lock(Mutex *mutex);
    };
    
    int main() {
        Lock /* lock */ (&mtx);
        return 0;
    }
    

    I get this compiler warning when compiling with DJGPP:

    C:\df>gxx -c a.cpp
    a.cpp: In function 'int main()':
    a.cpp:8:30: error: 'mtx' declared as reference but not initialized
    

    It compiles fine if I uncomment "lock" and add a mutex variable.

    So if your "mtx" variable is a pointer. What happens if you change it and pass it as "&mtx" instead.

    0 讨论(0)
  • 2020-12-17 19:02

    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();
    

    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.

    0 讨论(0)
  • 2020-12-17 19:11

    Note that your proposed warning will also be issued for every it++;, which is found in many for loops.

    iammilind has already mentioned that sometimes it is by intention to create and immediatly destroy the temp: when there are side-effects.

    And in template meta programming, one might create and destroy a temporary, just in case the user supplies a class with side-effects. When a simple class, without side-effects, is used to instantiate the template, warnings will appear deep down in the template code.

    Therefor, your proposed warning will have many false positives. It will be hard to find the genuine warnings among the spurious ones.

    So I expect that compiler vendors have decided that their time is better spent elsewhere.

    0 讨论(0)
提交回复
热议问题