Search code examples
c++movestdvectormove-semantics

Does std::move guarantee vector.data() does not change?


Consider the following code:

#include <vector>
#include <utility>
#include <cstdint>
#include <bit>

template <typename T>
std::pair<std::vector<uint8_t>, T*> create_data_vec() 
{
    std::vector<uint8_t> data(sizeof(T));
    auto ptr = std::bit_cast<T*>(data.data());
    return {std::move(data), ptr};
}

In C++20, is ptr guaranteed to point to the same data after returning? I tested this on gcc 11.3, and it holds, but does the standard guarantee it?

Example: https://godbolt.org/z/bG3rda3Ws

Note that this is not the final code. There is some placement new stuff as well, so this is just a minimum working example.


Solution

  • From https://en.cppreference.com/w/cpp/container/vector/vector#Notes

    After container move construction (overload (8)), 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 [container.reqmts]/67, and a more direct guarantee is under consideration via LWG issue 2321.

    So yes it is guaranteed.