Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the front address of std::vector move invariant?

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.

like image 803
Teodor Nikolov Avatar asked Jul 25 '18 19:07

Teodor Nikolov


People also ask

Does STD move invalidate pointers?

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.

What is the use of std :: 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.

Where is std :: move defined?

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.

Does C++ automatically move?

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.


1 Answers

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.

like image 86
François Andrieux Avatar answered Sep 28 '22 03:09

François Andrieux