c++ - Directly write into char* buffer of std::string -


so have std::string , have function takes char* , writes it. since std::string::c_str() , std::string::data() return const char*, can't use them. allocating temporary buffer, calling function , copying std::string.

now plan work big amount of information , copying buffer have noticeable impact , want avoid it.

some people suggested use &str.front() or &str[0] invoke undefined behavior?

c++98/03

impossible. string can copy on write needs handle reads , writes.

c++11/14

in [string.require]:

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

so &str.front() , &str[0] should work.

c++17

str.data(), &str.front() , &str[0] work.

here says:

chart* data() noexcept;

returns: pointer p such p + == &operator[](i) each i in [0, size()].

complexity: constant time.

requires: program shall not alter value stored at p + size().

the non-const .data() works.

the recent draft has following wording .front():

const chart& front() const;

chart& front();

requires: !empty().

effects: equivalent operator[](0).

and following operator[]:

const_reference operator[](size_type pos) const;

reference operator[](size_type pos);

requires: pos <= size().

returns: *(begin() + pos) if pos < size(). otherwise, returns reference object of type chart value chart(), modifying object leads undefined behavior.

throws: nothing.

complexity: constant time.

so uses iterator arithmetic. need inspect information iterators. here says:

3 basic_string contiguous container ([container.requirements.general]).

so need go here:

a contiguous container container supports random access iterators ([random.access.iterators]) , member types iterator , const_iterator contiguous iterators ([iterator.requirements.general]).

then here:

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

apparently, contiguous iterators c++17 feature added in these papers.

the requirement can rewritten as:

assert(*(a + n) == *(&*a + n)); 

so, in second part dereference iterator, take address of value points to, pointer arithmetic on it, dereference , it's same incrementing iterator , dereferencing it. means contiguous iterator points memory each value stored right after other, hence contiguous. since functions take char* expect contiguous memory, can pass result of &str.front() or &str[0] these functions.


Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -