Quuxplusone / LLVMBugzillaTest

0 stars 0 forks source link

False positives and false negatives for unused variable checks with structured binging #37001

Open Quuxplusone opened 6 years ago

Quuxplusone commented 6 years ago
Bugzilla Link PR38028
Status NEW
Importance P normal
Reported by Vladimir Pervouchine (vpervouchine@gmail.com)
Reported on 2018-07-03 00:33:51 -0700
Last modified on 2018-07-11 02:07:35 -0700
Version 6.0
Hardware PC Linux
CC blitzrakete@gmail.com
Fixed by commit(s)
Attachments
Blocks
Blocked by
See also
When I use structured binding to loop over a map:

for (auto const& [k, v]: my_map) {
   // do something with the key
   // do something with the value
}

I get an "unused variable" error in some code (even though both k and v are
used) and do not get the error in other code (where either k or v is really not
used). Unfortunately, I only managed to create a toy example to demonstrate the
latter so far: https://godbolt.org/g/oUFNJm

#include <map>
#include <iostream>

struct Abc {
    int a;
    int b;
    float c;
};

using MapKey = std::tuple<int, int>;
using MapValue = Abc;

using Map = std::map<MapKey, MapValue>;

int main() {

    Map m;
    m.emplace(std::make_tuple(1, 1), MapValue{1, 2, 3.0});
    m.emplace(std::make_tuple(1, 2), MapValue{2, 3, 4.0});

    for (auto const& [key, value]: m) {
        std::cout << std::get<0>(key) << std::endl;
    }
}

Compile flags: -O3 -std=c++1z -Werror -Wunused-variable
Quuxplusone commented 6 years ago

I can't say anything about the first one, but the latter case is a feature, not a bug.

Normally, if you have an unused variable, you could remove it to silence the warning. But in a structured binding, you can't (you can't even use [[maybe_unused]]) and IIRC this was an explicit design decision.