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


i'm fighting old c-style-interface. have function signature this:

 /// if return_value == null length returned  void f( char * return_value, size_t * size_only_known_at_runtime);  

my question is, following code safe?

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

is there better way data string?

yes, it's safe, @ least explicitly c++11. [string.require], emphasis mine:

the char-like objects in basic_string object shall stored contiguously. is, basic_string object s, identity &*(s.begin() + n) == &*s.begin() + n shall hold values of n such 0 <= n < s.size().

this resolution of dr 530. before c++11, not explicit in standard, although done in practice anyway.

in c++14, requirement got moved [basic.string]:

a basic_string contiguous container (23.2.1).

where [container.requirements.general]:

a contiguous container container supports random access iterators (24.2.7) , member types iterator , const_iterator contiguous iterators (24.2.1).

where [iterator.requirements.general]:

iterators further satisfy requirement that, integral values n , dereferenceable iterator values a , (a + n), *(a + n) equivalent *(addressof(*a) + n), called contiguous iterators.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -