Reuse a moved object

suggest change

An object of a standard-library type can generally be reused after it has been moved from. Unless a type documents a stronger guarantee, its state is valid but unspecified: its invariants still hold and it may be destroyed or assigned to, but code should not assume which value it contains.

#include <utility>
#include <vector>

void consumingFunction(std::vector<int> vec) {
    // Some operations
}

int main() {
    // initialize vec with 1, 2, 3, 4
    std::vector<int> vec{1, 2, 3, 4};

    // Send the vector by move
    consumingFunction(std::move(vec));

    // vec is valid but has an unspecified value. Assigning to it is safe.
    vec = {};

    // vec now has a known value and can be used normally.
    vec.push_back(42);

    // Send the vector by move again.
    consumingFunction(std::move(vec));
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents