Home > Backend Development > C++ > body text

Can You Move From a Const Object in C ?

Patricia Arquette
Release: 2024-11-18 09:49:02
Original
643 people have browsed it

Can You Move From a Const Object in C  ?

Understanding std::move on const Objects: Unveiling the Performance Pitfall

In C , the std::move function is used to transfer ownership of an object. However, a common question arises: why is it possible to call std::move on a const object? Isn't this counterintuitive and potentially dangerous?

The trick lies in the fact that std::move(const_object) doesn't perform an actual move. Instead, it instructs the compiler to attempt a move. If the class doesn't have a constructor that accepts a const reference to an rvalue (move constructor), the compiler will default to the implicit copy constructor.

Consider the following example:

struct Cat {
   Cat(){}
   Cat(const Cat&amp;) {std::cout << "COPY";}
   Cat(Cat&amp;&amp;) {std::cout << "MOVE";}
};

int main() {
    const Cat cat;
    Cat cat2 = std::move(cat); // prints "COPY"
}
Copy after login

As you can see, even though cat is a const object, the compiler safely constructs cat2 as a copy. This is because there's no move constructor available for const objects in this example.

The potential pitfall highlighted by Scott Meyers in "Effective Modern C " is a performance issue rather than a stability issue. In essence, attempting to move from a const object when a move constructor isn't available will result in a less efficient copy.

While it might seem logical to restrict std::move from operating on const objects, it's not a straightforward solution due to the following reasons:

  • It would not prevent all cases of unintended copying since it's still possible for non-const objects to lack a move constructor.
  • It would interfere with generic template code that intentionally uses the fallback copy constructor.
  • It would restrict cases where a move constructor from a const object might be intentionally desired.

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