Home >Backend Development >C++ >What Can You Do with a Moved-From Object in C ?

What Can You Do with a Moved-From Object in C ?

Susan Sarandon
Susan SarandonOriginal
2024-12-25 12:03:09571browse

What Can You Do with a Moved-From Object in C  ?

What Operations are Permitted on Moved-From Objects?

The C standard defines the behavior of objects that have been moved from. This knowledge is crucial for understanding how certain functions, such as std::swap, work.

Standard Definition

According to the standard (section 17.6.5.15), objects from C standard library types can be moved and are subsequently placed in a "valid but unspecified state."

Implication for Operations

When an object is in an unspecified state, you can perform any operation that does not have preconditions. Preconditionless operations include:

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

However, operations with preconditions generally cannot be performed without further checking. For example:

  • Dereference
  • pop_back

Example: std::swap

The std::swap function, as shown in the original question, requires assignment to moved-from objects. This is possible because assignment is a preconditionless operation.

Additional Note: T c = std::move(a) vs. T c(std::move(a))

In the std::swap implementation, a direct move assignment T c = std::move(a) is used instead of a copy constructor T c(std::move(a)). This is done to avoid an unnecessary copy of a, which would result in a performance penalty.

The above is the detailed content of What Can You Do with a Moved-From Object in C ?. 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