llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
28.05k stars 11.58k forks source link

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

Open llvmbot opened 6 years ago

llvmbot commented 6 years ago
Bugzilla Link 38028
Version 6.0
OS Linux
Reporter LLVM Bugzilla Contributor

Extended Description

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

include

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

llvmbot 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.