Home > Backend Development > C++ > When Is a Moved-From Vector Not Empty?

When Is a Moved-From Vector Not Empty?

Susan Sarandon
Release: 2024-12-01 11:17:14
Original
990 people have browsed it

When Is a Moved-From Vector Not Empty?

Is a Moved-From Vector Always Empty?

Question:

It is known that objects of standard library types can be moved from, and while move operations may leave moved-from objects in an unspecified state, there are no explicit requirements excluding vector from this. However, how is it possible for moved-from vectors to be in a non-empty state?

Answer:

Generally, a moved-from vector will be empty, but it is not always the case.

Specific Cases:

The behavior of a moved-from vector depends on the operation used (move constructor or move assignment) and the allocator associated with the vector.

Move Constructor:

vector(vector&& v)

In this case, the moved-from vector will always be empty. The move operation requires constant complexity, necessitating the transfer of ownership from one vector to another, leaving the former empty.

Move Assignment:

vector& operator=(vector&& v)

There are three scenarios to consider:

  1. Allocator Propagation Enabled: The moved-from vector will always be empty.
  2. Allocator Propagation Disabled and Equal Allocators: The behavior is similar to the first scenario, leaving the moved-from vector empty.
  3. Allocator Propagation Disabled and Different Allocators: The moved-from vector may retain its elements. The move assignment operation is forced to use individual move operations to transfer elements, potentially leaving the original elements intact.

It should be noted that some implementations may choose to explicitly clear the moved-from vector in this scenario, but it is not a requirement.

The above is the detailed content of When Is a Moved-From Vector Not 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