Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to use operator [] for std::string

I'm fighting with an old c-style-interface. I have a function with a signature like this:

 /// if return_value == NULL only the length is returned
 void f( char * return_value, size_t * size_only_known_at_runtime); 

My question is, is the following code safe?

std::size required;
f( NULL, &required );
std::string s;
s.resize(required);
f( &s[0], &required );

Is there a better way to get the data into the string?

like image 711
user1235183 Avatar asked Jan 08 '23 09:01

user1235183


1 Answers

Yes, it's safe, at least explicitly from C++11. From [string.require], emphasis mine:

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().

This was the resolution of DR 530. Before C++11, this was not explicit in the standard, although it was done in practice anyway.

In C++14, this requirement got moved to [basic.string]:

A basic_string is a contiguous container (23.2.1).

where [container.requirements.general]:

A contiguous container is a container that supports random access iterators (24.2.7) and whose member types iterator and const_iterator are contiguous iterators (24.2.1).

where [iterator.requirements.general]:

Iterators that further satisfy the requirement that, for integral values n and dereferenceable iterator values a and (a + n), *(a + n) is equivalent to *(addressof(*a) + n), are called contiguous iterators.

like image 51
Barry Avatar answered Jan 17 '23 22:01

Barry