Home > Backend Development > C++ > How to Safely Reuse a Moved Container in C 0x?

How to Safely Reuse a Moved Container in C 0x?

DDD
Release: 2024-12-02 16:24:12
Original
600 people have browsed it

How to Safely Reuse a Moved Container in C  0x?

Reusing a Moved Container: Exploring the C 0x Standard Draft

The question at hand seeks to clarify the proper method for reusing a moved container in C . According to the C 0x standard draft, an object in a "valid but unspecified state" allows operations that do not require preconditions unless said preconditions are first verified.

Consider the code snippet provided:

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
Copy after login

The vector container is moved to container2, leaving container in an unspecified state. According to the standard, this state allows operations without preconditions. Hence, calling clear on container2 (version 2) will return it to a known state.

Alternatively, reinitializing container using version 3 will also achieve the desired result. This method is slightly more roundabout but allows for potential optimization. However, it can also lead to mistakes.

Therefore, the correct method for reusing a moved container is either to clear it or reinitialize it. Version 2 is preferred as it explicitly resets the container to a known state and avoids potential pitfalls associated with version 3.

The above is the detailed content of How to Safely Reuse a Moved Container in C 0x?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template