Contiguous Iterators

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3884.pdf

Is using &*myvec.begin() as a buffer undefined behavior until C++1z?
The elements of a vector are stored contiguously, meaning that if v is a vector<T, Allocator> where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size(). - IS


Unless the value_type is hard-coded, favour std::addressof():
1
2
3
4
5
if( !myvec.empty() )
{
    auto buffer = std::addressof( myvec.front() ) ;
    // ...
}
Is using &*myvec.begin() as a buffer undefined behavior until C++1z?

No. std::vector's storage was guaranteed to be contiguous by the 2003 amendment to the C++98 standard. [Edit: following JLBorges' post]

(Not sure an iterator can be contiguous? &*myvec.begin() finds the address of the first element, so the issue is whether or not the elements in the container are stored contiguously.)

Andy

PS While std::vector is the only container in C++98 C++03 for which this is true, the C++11 standard also guarantees that std::string's storage is contiguous.

The char-like objects in a basic_string object shall be stored contiguously. That is, for any basic_string
object s, the identity &*(s.begin() + n) == &*s.begin() + n shall hold for all values of n such that 0
<= n < s.size().

And makes the same guarantee for the new C++ container type std::array.
Last edited on
For the record, the C++98 standard did not explicitly guarantee contiguous storage for the objects in std::vector<>. It was the 2003 amendment to the standard that added the contiguity guarantee.

In practice, the old standard also required contiguous storage for the characters in std::string.
But it did not extend that requirement to include the-notional-one-past-the-last-element [ end() ];
c_str() was not guaranteed to be O(1).

data() was required to return "a pointer to the initial element of an array whose first size() elements equal the corresponding elements of the string controlled by *this"

and operator[pos] was required to return "data()[pos]" if pos < size().
Thanks guys, this is good information to be aware of.
Topic archived. No new replies allowed.