In the following snippet:
std::vector<double> a(100, 4.2);
auto* a_ptr = a.data();
auto b = std::move(a);
auto* b_ptr = b.data();
std::cout << ((b_ptr == a_ptr) ? "TRUE" : "FALSE") << '\n';
does the C++ standard guarantee that b_ptr
is always equal to a_ptr
after std::move
? Running the code on wandbox prints TRUE
.
No. They will point to the local object that's been moved from; as described above, you can't make any assumptions about that object's state after the move.
std::move is used to indicate that an object t may be "moved from", i.e. allowing the efficient transfer of resources from t to another object. In particular, std::move produces an xvalue expression that identifies its argument t . It is exactly equivalent to a static_cast to an rvalue reference type.
Move Constructor And Semantics: std::move() is a function used to convert an lvalue reference into the rvalue reference. Used to move the resources from a source object i.e. for efficient transfer of resources from one object to another. std::move() is defined in the <utility> header.
That's pretty much the only time you should write std::move , because C++ already uses move automatically when copying from an object it knows will never be used again, such as a temporary object or a local variable being returned or thrown from a function. That's it.
From cppreference.com :
After container move construction (overload (6)), references, pointers, and iterators (other than the end iterator) to other remain valid, but refer to elements that are now in *this. The current standard makes this guarantee via the blanket statement in §23.2.1[container.requirements.general]/12, and a more direct guarantee is under consideration via LWG 2321.
Pointers to elements are not invalidated, including pointers to the first element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With