Home >Backend Development >C++ >What are the Validity and Allowable Operations on Moved-From Objects in C 11?

What are the Validity and Allowable Operations on Moved-From Objects in C 11?

Linda Hamilton
Linda HamiltonOriginal
2024-12-06 09:34:12500browse

What are the Validity and Allowable Operations on Moved-From Objects in C  11?

Validity of Moved-From Objects in C 11

Understanding the validity of moved-from objects in C 11 can be complex. This article aims to clarify the concept, particularly in the context of pimpl objects.

Moved-From Objects

When an object is moved from, its state becomes unspecified. The standard library defines the validity criteria for standard library types, ensuring that moved-from objects are placed in a valid but unspecified state. However, for custom types, it is the developer's responsibility to define and document the valid state and allowable operations for moved-from objects.

Example: Pimpl Idiom

In the example pimpl idiom, the impl_ member points to a dynamic allocation. After a move operation, the pointer in the moved-from object is set to nullptr. This renders the do_stuff() method invalid, as it attempts to dereference the impl_ pointer.

Invariant vs. Valid State

The invariant that a Foo object can always do_stuff() is no longer valid after being moved from. In general, moved-from objects may not satisfy all invariants that apply to their non-moved counterparts.

Option 1: Checked Operation

One option is to explicitly check if the impl_ pointer is nullptr in do_stuff() and initialize it if necessary. However, this introduces a potential performance overhead.

Option 2: Define Invalid State

Alternatively, the code can explicitly define that moved-from Foo objects are in an invalid state and that calling do_stuff() on them will result in an error.

Concepts and Moved-From Objects

It's important to note that the concepts defined by the standard library do not consider moved-from objects. To meet the requirements of concepts, moved-from objects of custom types must still fulfill the concept requirements.

Conclusion

Understanding the validity of moved-from objects is crucial for implementing move semantics correctly. Developers should carefully consider the implications of move operations on the state of their objects and define the expected behavior accordingly.

The above is the detailed content of What are the Validity and Allowable Operations on Moved-From Objects in C 11?. 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