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&) {std::cout << "COPY";} Cat(Cat&&) {std::cout << "MOVE";} }; int main() { const Cat cat; Cat cat2 = std::move(cat); // prints "COPY" }
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:
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!