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

What Operations Are Allowed on Moved-From C Objects?

Patricia Arquette
Release: 2025-01-01 14:08:10
Original
833 people have browsed it

What Operations Are Allowed on Moved-From C   Objects?

Allowed Operations on Moved-From Objects

The C standard defines what actions are permissible with objects that have been moved from. These objects are considered to be in an unspecified state, allowing for a limited range of operations.

Standard Reference

Section 17.6.5.15 [lib.types.movedfrom] of the standard states that moved-from objects "shall be placed in a valid but unspecified state."

Non-Restrictive Operations

Objects in an unspecified state can undergo operations that do not have preconditions. Common examples include:

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

Restrictive Operations

Operations with preconditions, such as dereferencing or pop_back, cannot be performed directly on moved-from objects, as the object's unspecified state may not satisfy the necessary requirements.

Example: std::swap

The example swap function template relies on assignments to moved-from objects (lines 2 and 3). This is valid because assignment is a non-restrictive operation.

Alternative Constructor Syntax

Regarding line 1, the use of T c = std::move(a); instead of T c(std::move(a)); is for efficiency reasons. Direct initialization requires a copy constructor call, while assignment does not.

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