Home >Backend Development >C++ >Why Can You Use `std::move` on Constant Objects in C ?
Why std::Move Can Be Used on Constant Objects
Generally, invoking std::move on a constant object would seem illogical since one expects to move, or modify, the object. However, in C 11, the use of std::move on constant objects is allowed.
To elaborate, std::move(cat) doesn't imply that the object is actually moved. Instead, it instructs the compiler to attempt the move. In cases where the class doesn't define a constructor that accepts a const reference to an rvalue (e.g., const Cat&&), the compiler will use the implicit const reference to an lvalue copy constructor, thus performing a safe copy instead.
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); }
Even though std::move is used, the "COPY" message will be output, indicating that the object was copied instead of moved.
This behavior serves as a safety mechanism. If the copy constructor is disabled, the compiler will prompt the developer with an error message.
Furthermore, the bug mentioned in Scott Meyers' book 'Effective Modern C ' is not a stability issue but a performance concern. It occurs when an implicit copy is performed when a move is intended, resulting in slower execution. Additionally, such bugs can occur even with non-const objects that lack move constructors.
Ultimately, allowing std::move to operate on constant objects provides flexibility. Developers retain the ability to explicitly construct objects from const rvalue references if desired.
The above is the detailed content of Why Can You Use `std::move` on Constant Objects in C ?. For more information, please follow other related articles on the PHP Chinese website!