Skip to content

[clang-tidy] Check request: call-std-swap-universally-in-generic #130444

@denzor200

Description

@denzor200

Needs a check that will find a call to std::swap which compiles with only bounded set of objects, and not intended to be in generic code, but it is.
For example:

template<typename T>
void process(T& a, T& b) {
    {
        std::swap(a, b); // (1) BAD
    }
    {
        swap(a, b);      // (2) BAD
    }
    {
        a.swap(b);       // (3) BAD
    }
    {
        using std::swap;
        swap(a, b);      // OK
    }
}

void nongeneric_code_0(int& a, int& b) {
    std::swap(a, b);     // OK
}
void nongeneric_code_1(Cookie& a, Cookie& b) {
    swap(a, b);          // OK
}

Here is the full snippet to play: https://godbolt.org/z/r9hGTjed5

The check will suggest to change the code for (1) BAD and (2) BAD, but for (3) BAD no change will be suggested, only warning produced.
For both bad cases before C++20 the following fix will be suggested:

using std::swap;
swap(a, b);

In C++20 and later we should propose shorter fix:

std::ranges::swap(a, b);

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions