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?
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 ofn
such that0 <= 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
andconst_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 valuesa
and(a + n)
,*(a + n)
is equivalent to*(addressof(*a) + n)
, are called contiguous iterators.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With