Home >Backend Development >C++ >What Operations Are Valid on C Moved-From Objects?

What Operations Are Valid on C Moved-From Objects?

Barbara Streisand
Barbara StreisandOriginal
2024-12-25 17:42:15173browse

What Operations Are Valid on C   Moved-From Objects?

What Objects Can Be Moved From?

The C standard allows objects of types defined in the C standard library to be moved from. This means that a new object can be created and initialized with the data from an existing object, which is then moved into an unspecified state.

Valid Operations on Moved-From Objects

The standard defines that moved-from objects shall be placed in a valid but unspecified state. This means that any operation with no preconditions can be performed on a moved-from object. Such operations typically include:

  • Destruction
  • Assignment
  • Const observers (e.g., get, empty, size)

Operations with Preconditions

Operations that generally do have preconditions, such as dereference and pop_back, cannot be directly performed on moved-from objects.

Example: Swap Function Template

The swap function template in the standard library demonstrates the ability to assign to moved-from objects. In this function, the moved-from object is first assigned to a temporary variable (line 1). The original object is then assigned the value of the other object (line 2) before being assigned the value of the temporary variable (line 3).

Note on Initialization Syntax

The use of T c = std::move(a) in line 1 instead of T c(std::move) is not relevant to the discussion of move operations. It is simply a matter of style and preference.

The above is the detailed content of What Operations Are Valid on C Moved-From Objects?. 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