我可以将已移动的变量标记为不再可用并在使用它时收到编译器警告吗?

Can I mark a moved variable as no longer usable and receive a compiler warning if I do use it?

有时在一个函数中我使用 std::move 传递一个我不再使用的变量,像这样:

void f(std::vector<int> v)
{
    for (int i: v)
    {
        std::cout << i << ", ";
    }
}

void main()
{
    std::vector<int> v(1000);
    std::fill(v.begin(), v.end(), 42);
    f(std::move(v));
}

我了解 std::move 使我的向量处于有效状态,因此我可以调用 v.clear() 并在需要时重新使用它。但是在一个长函数中,我稍后可能会向它添加更多代码,而忘记我已经用我的移动函数丢失了数据,从而引入了一个错误。

我可以在移动后放置某种编译器指令来警告我不要重用这个变量吗?像这样:

void main()
{
    std::vector<int> v(1000);
    std::fill(v.begin(), v.end(), 42);
    f(std::move(v));
    #pragma mark_unusable(v);

    // This should trigger a compiler warning
    v.clear();
}

部分答案:您可以使用 clang-tidy 及其 bugprone-use-after-move 检查。在您的示例中,这不会捕获 v.clear() ,但至少会捕获其他情况。示例:

clang-tidy -checks=bugprone-use-after-move your-file.cpp

当您在第一次调用后添加第二个 f(std::move(v)); 时,您会得到

your-file.cpp:15:17: warning: 'v' used after it was moved [bugprone-use-after-move]
f(std::move(v));
            ^
your-file.cpp:14:5: note: move occurred here
f(std::move(v));
^