Skip to content

[clang-tidy] Check request: modernize-use-std-exchange #133110

@denzor200

Description

@denzor200

Needs a check that will find places in the code with potential for using std::exchange and will suggest using it.

At least this feature should be implemented for checking move-constructors and move-assignments.

BEFORE:

struct S
{
    int n;
 
    S(S&& other) noexcept {
        n = other.n;
        other.n = 0;
    }

    S& operator=(S&& other) noexcept {
        if (this != &other) {
            n = other.n;
            other.n = 0;
        }
        return *this;
    }
};

AFTER:

struct S
{
    int n;
 
    S(S&& other) noexcept {
        n = std::exchange(other.n, 0);
    }

    S& operator=(S&& other) noexcept {
        n = std::exchange(other.n, 0);
        return *this;
    }
};

Also I suppose it's possible to implement checking of regular functions.

BEFORE:

class stream
{
public:
    int flags(int newf) {
        const int old_flags = flags_;
        flags_ = newf;
        return old_flags;
    }
private:
    int flags_ = 0;
};

AFTER:

class stream
{
public:
    int flags(int newf) { return std::exchange(flags_, newf); }
private:
    int flags_ = 0;
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions