Search code examples
c++clangllvmc++builder

Is there a compile warning about this use of std::move?


The following program shows two problematic (but technically valid) uses of std::move(). Is it possible to get a compile warning about these with LLVM? I have noticed that there is diagnostic for some other contexts where std::move is redundant.

I compiled this with bcc32c version 5.0.2 (based on LLVM 5.0.2) and received no warnings.

#include <vector>

int main() {
    const std::vector<int> a = {1, 2, 3};
    std::vector<int> b = {3, 4, 5};

    std::vector<int> c = std::move(a); // std::move from const

    std::vector<int> d = std::move(b);

    std::vector<int> e = b; // used after std::move
}

Solution

  • clang-tidy's bugprone-use-after-move checker supports this kind of diagnostic:

    bugprone-use-after-move

    Warns if an object is used after it has been moved, for example:

    std::string str = "Hello, world!\n";
    std::vector<std::string> messages;
    messages.emplace_back(std::move(str));
    std::cout << str;
    

    The last line will trigger a warning that str is used after it has been moved.

    [...]

    Use

    Any occurrence of the moved variable that is not a reinitialization (see below) is considered to be a use.

    [...]

    If multiple uses occur after a move, only the first of these is flagged.