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

Is a Moved-From `std::vector` Always Empty?

Barbara Streisand
Barbara StreisandOriginal
2024-11-18 03:36:02905browse

Is a Moved-From `std::vector` Always Empty?

Is a Moved-From Vector Always Empty?

Moving objects in C leaves them in an unspecified state. While there is no explicit exclusion for vectors in this rule, finding a feasible implementation that wouldn't result in an empty vector can be challenging.

Move Constructor

The move constructor for vectors must have constant complexity. This necessitates stealing resources from the moved-from vector, leaving it empty. Therefore, for the move constructor, the moved-from vector is always empty.

Move Assignment Operator

The behavior of the move assignment operator depends on the vector's allocator. There are three main cases:

Case 1:
Propagate_on_container_move_assignment is true.

In this case, destruction, deallocation, allocator movement, and memory buffer transfer occur, leaving the moved-from vector empty.

Case 2:
Propagate_on_container_move_assignment is false, but allocators are equal.

Similar to Case 1, the moved-from vector is emptied.

Case 3:
Propagate_on_container_move_assignment is false, and allocators are unequal.

It's impossible to transfer resources directly. Instead, elements must be moved individually. If the moved-from vector contains elements without move constructors, it will remain non-empty. However, the implementation could optionally call v.clear() to empty it, although this is not required by the standard.

The above is the detailed content of Is a Moved-From `std::vector` Always Empty?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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