Home > Backend Development > C++ > How Should You Reuse a Moved C Container?

How Should You Reuse a Moved C Container?

Linda Hamilton
Release: 2024-12-04 19:58:11
Original
705 people have browsed it

How Should You Reuse a Moved C   Container?

Reusing a Moved Container: Ensuring Correct Behavior

When a container is moved, it is placed in a "valid but unspecified state" according to the C 0x standard draft. In such a situation, it's crucial to understand how to reuse the moved container correctly.

Consider the following code snippet:

std::vector<int> container;
container.push_back(1);
auto container2 = std::move(container);

// ver1: Do nothing
//container2.clear(); // ver2: "Reset"
container = std::vector<int>() // ver3: Reinitialize

container.push_back(2);
assert(container.size() == 1 && container.front() == 2);
Copy after login

According to the standard, option ver3, which involves reinitializing the moved container, is the correct approach. This is because, after a move operation, an object is placed in an unspecified state.

The standard defines a "valid but unspecified state" as follows:

"an object state that is not specified except that the object’s invariants are met and operations on the object behave as specified for its type"

This means that the moved-from object remains live and can be operated on, but only if preconditions are met. In the case of a vector, clearing the container with clear() has no preconditions and returns it to a known state.

Therefore, the recommendation is to use clear() to reset a moved container and return it to a usable state.

Option ver2, which involves calling clear() on the moved container, is also valid. However, it may lead to optimizations assuming the moved container is empty. Using clear() ensures that the container is returned to a known state, regardless of optimizations.

Option ver1, which involves doing nothing, is not recommended. This is because the container is in an unspecified state after the move and may exhibit unexpected behavior.

The above is the detailed content of How Should You Reuse a Moved C Container?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template