Muokkaa

Jaa


Warning C26800

Use of a moved from object: 'object'.

Remarks

Warning C26800 is triggered when a variable is used after it has been moved from. A variable is considered moved from after it's passed to a function as rvalue reference. There are some exceptions for assignment, destruction, and some state resetting functions such as std::vector::clear. After using a state resetting function, we're free to use the variable. This check only reasons about the local variables.

The following methods are considered state resetting methods:

  • Functions with the following case-insensitive substring in their name: clear, clean, reset, free, destroy, release, dealloc, assign
  • Overloaded assignment operators, destructor

This check respects the std::swap operation:

void f() {
    Y y1, y2;
    consume(std::move(y1));
    std::swap(y1, y2);
    y1.method();                  // OK, valid after swap.
    y2.method();                  // warning C26800
}

The check also supports the try_emplace operations in STL that conditionally move its argument:

int g() {
  std::map<int, Y> m;
  Y val;
  auto emplRes = m.try_emplace(1, std::move(val));
  if (!emplRes.second) {
    val.method();  // No C26800, val was not moved because the insertion did not happen.
  }
}

Code analysis name: USE_OF_A_MOVED_FROM_OBJECT

Examples

The following code generates C26800.

#include <utility>

struct X {
    X();
    X(const X&);
    X(X&&);
    X &operator=(X&);
    X &operator=(X&&);
    ~X();
};

template<typename T>
void use_cref(const T&);

void test() {
    X x1;
    X x2 = std::move(x1);
    use_cref(x1);                // warning C26800
}

The following code doesn't generate C26800.

#include <utility>

struct MoveOnly {
    MoveOnly();
    MoveOnly(MoveOnly&) = delete;
    MoveOnly(MoveOnly&&);
    MoveOnly &operator=(MoveOnly&) = delete;
    MoveOnly &operator=(MoveOnly&&);
    ~MoveOnly();
};

template<typename T>
void use(T);

void test() {
    MoveOnly x;
    use(std::move(x)); // no 26800
}