Home > Backend Development > C++ > Is a Moved-From `std::vector` Guaranteed to Be Empty?

Is a Moved-From `std::vector` Guaranteed to Be Empty?

Susan Sarandon
Release: 2024-11-18 03:04:02
Original
318 people have browsed it

 Is a Moved-From `std::vector` Guaranteed to Be Empty?

Is a Moved-From Vector Guaranteed to Be Empty?

In general, the C standard provides minimal guidance on the state of objects after they have been moved from. As stated in N3485 17.6.5.15 [lib.types.movedfrom]/1:

Objects of types defined in the C standard library may be moved from (12.8). Move operations may be explicitly specified or implicitly generated. Unless otherwise specified, such moved-from objects shall be placed in a valid but unspecified state.

While this provision doesn't exclude vector from being subject to this behavior, it leaves room for interpretation.

Vector's Specific Behavior

There is no explicit standard requirement that excludes vector from being affected by the general rule for moved-from objects. However, given the requirements for vector's implementation, there are limited options:

Move Constructor:

  • The move constructor must have constant complexity.
  • The only option is to steal resources from the source vector (v) to construct the new vector, leaving v empty.

Move Assignment Operator:

  • Behavior depends on the vector's allocator:

Case One:

Case Two:

Case Three:

Conclusion:

For vector's move constructor, the moved-from vector is always empty. For the move assignment operator, the moved-from vector is usually empty, but may not be in certain specific scenarios where allocators are not compatible and T is MoveAssignable or MoveInsertable.

The above is the detailed content of Is a Moved-From `std::vector` Guaranteed to Be Empty?. 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