4 ms·
Watch out! "&(v[0])" has undefined behavior if v is empty. "v.data()" always works, besides being more readable.
by DerekL 12y ago
Watch out! "&(v[0])" has undefined behavior if v is empty. "v.data()" always works, besides being more readable.
- robotresearcher 12y agoI looked this up: "Returns pointer to the underlying array serving as element storage. The pointer is such that range [data(); data() + size()) is always a valid range, even if the container is empty." Can someone explain the semantics? If the range is valid for an empty vector, what does that say about the validity of tge pointer returned? What value will it have for an empty vector?
- SamReidHughes 12y agoThe pointer will have a non-trap representation, if that is even a thing in C++. I wouldn't even assume it's non-null or not a value shared between different vectors. You can also add or subtract 0 to the pointer, or subtract the pointer from itself.
- DerekL 12y agoOn an empty vector, data() can either return a null pointer, or a pointer to some allocated memory with suitable alignment for that type, but there doesn't have to be a existing object. What is the range [ data(), data() + size() ) anyway? It consists of n + 1 iterators. All but the last one can be dereferenced. You can take one iterator in the range and add or subtract to get another one, as long as you stay in the range. You can subtract iterators to get a signed integer. You can compare iterators with all six operators ==, !=, <, >, <= and >=. For any valid pointer p, null or not, [p, p) is a valid range of length 0. It has one iterator, p, but you can't dereference it. You can add or subtract 0. You can subtract p from itself, getting 0. And you can compare it with itself.