llvm / llvm-project

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

`performance-unnecessary-copy-initialization` not detected #98005

Open firewave opened 4 months ago

firewave commented 4 months ago
#include <list>

class V {};

struct S
{
    std::list<V> argumentList;
};

void f()
{
    S s;
    const auto argList = s.argumentList; // should use reference
    if (argList.empty()) {}
}

https://godbolt.org/z/31r8d3vfP

llvmbot commented 4 months ago

@llvm/issue-subscribers-clang-tidy

Author: Oliver Stöneberg (firewave)

```cpp #include <list> class V {}; struct S { std::list<V> argumentList; }; void f() { S s; const auto argList = s.argumentList; // should use reference if (argList.empty()) {} } ``` https://godbolt.org/z/31r8d3vfP
firewave commented 4 months ago

A more simplified case is being detected:

#include <string>

void f()
{
    std::string str;
    const auto s = str;
    if (s.empty()) {}
}
<source>:6:16: warning: local copy 's' of the variable 'str' is never modified; consider avoiding the copy [performance-unnecessary-copy-initialization]
    6 |     const auto s = str;
      |                ^
      |               &

https://godbolt.org/z/q364bT1h6

chrchr-github commented 3 months ago

Small variations prevent detection:

void f()
{
    std::string str;
    //const auto s = std::string(str.begin(), str.end()); // FN
    const std::string s(str.begin(), str.end()); // FN
    if (s.empty()) {}
}

https://godbolt.org/z/x96KP6zEv