dimanche 7 janvier 2018

With std::vector why is &vec[0] UB but vec.data() safe?

I've been reading through the FAQ at isocpp.org at "Link here" and came across the caution that with an std::vector:

std::vector<int> v;
auto a = &v[0]; // Is undefined behaviour but
auto a = v.data(); // Is safe

From the actual site:

void g()
{
  std::vector<Foo> v;
  // ...
  f(v.begin(), v.size());  // error, not guaranteed to be the same as &v[0]
    ↑↑↑↑↑↑↑↑↑ // cough, choke, gag; use v.data() instead
}

Also, using &v[0] is undefined behavior if the std::vector or std::array is empty, while it is always safe to use the .data() function.

I'm not sure I've understood this exactly. ::data() returns a pointer to the beginning of the array, and &[0] returns the address of the beginning. I'm not seeing the difference here, and I don't think that &[0] is dereferencing anything (ie., is not reading the memory at element 0). On Visual Studio in debug build accessing subscript [0] results in an assertion failed, but in release mode doesn't say anything. Also the addresses in both cases is 0 for the default constructed vector.

Also I don't understand the comment about ::begin() not guaranteed to be the same as ::operator[0]. I assumed that for a vector the raw pointer in the begin() iterator, ::data(), and &[0] were all the same value.

Aucun commentaire:

Enregistrer un commentaire