Home > Backend Development > C++ > What are the Valid States of Moved-from Objects in C 11 and How to Define Them?

What are the Valid States of Moved-from Objects in C 11 and How to Define Them?

Barbara Streisand
Release: 2024-12-01 18:14:11
Original
383 people have browsed it

What are the Valid States of Moved-from Objects in C  11 and How to Define Them?

Understanding Valid States for Moved-from Objects in C 11

Move semantics in C 11 introduce a crucial concept: the state of objects after being moved from. However, the exact conditions that a moved-from object must satisfy can be confusing.

The Issue with pimpl Objects

Consider the pimpl idiom, where a class wraps a pointer to an implementation object. If we move from a Foo object (containing a std::unique_ptr), what can we do with it afterwards?

  • Destroying or assigning to it is safe.
  • Calling member functions (via the implementation pointer) is problematic, as it may reference a deleted object.

Standard Library Moved-from States

The C standard defines that moved-from objects of standard library types are placed in an "unspecified but valid state." This means that you can perform operations on them that have valid preconditions.

However, for non-standard types, you must define and document the valid state and operations allowed after being moved from.

Defining the Valid State for pimpl

In the Foo example, we could specify that moving from it renders the do_stuff function invalid. This would prevent us from accidentally invoking it on a moved-from object.

Avoiding Dynamic Allocations

To avoid the overhead of dynamic allocations when checking the valid state, consider using the "null object" pattern. This involves having a default FooImpl that is used when the object is in an invalid state.

Concepts and Moved-from Objects

Finally, note that moved-from objects must still meet the requirements of standard library concepts. If your type doesn't remain in a valid state, using it with standard library functions may result in undefined behavior.

The above is the detailed content of What are the Valid States of Moved-from Objects in C 11 and How to Define Them?. 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