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

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

Linda Hamilton
Release: 2024-11-29 02:33:09
Original
627 people have browsed it

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

Validity of Moved-from Objects in C 11

When an object is moved from in C 11, its state becomes unspecified, raising questions about what operations can be performed on it afterwards. While standard library types are moved to a valid but unspecified state, custom types require explicit definition to determine their valid state after being moved from.

In the case of pimpl objects, where the implementation is hidden behind a pointer, the question arises: what can be done with a Foo object once its pimpl pointer has been moved away? While destroying or reassigning the moved-from object remains safe, attempting operations like do_stuff will fail because the pimpl pointer has become invalid.

The standard design encourages a conservative approach by allowing unspecified states for moved-from objects to enable efficient implementation across different libraries. This requires querying the state of an object before performing operations on it, a task that can introduce performance overheads, especially in scenarios with a high frequency of move operations.

To avoid the need for such querying, custom types can explicitly specify their valid state after being moved from. For example, the pimpl class could declare that moving from it renders do_stuff invalid with undefined behavior. This approach ensures that users are aware of the possible consequences of moving from an object and can avoid potential errors.

It's worth noting that moved-from objects must still fulfill the requirements of any concepts defined by the standard library, which do not account for moved-from states. Therefore, custom types that do not maintain a valid state as defined by relevant concepts cannot be used with the standard library without risking undefined behavior.

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