Write char * std :: string directly to the buffer

So, I have std::stringand have a function that takes char*and writes to it. As std::string::c_str()and std::string::data()return statement const char*, I can not use them. Therefore, I allocated a temporary buffer by calling a function with it and copying it to std::string.

Now I plan to work with a large amount of information, and copying this buffer will have a noticeable effect, and I want to avoid it.

Some people suggested using &str.front()or &str[0], but does this cause undefined behavior?

+4
source share
3 answers

C ++ 98/03

. , .

++ 11/14

[string.require]:

char basic_string . basic_string s, &*(s.begin() + n) == &*s.begin() + n n , 0 <= n < s.size().

&str.front() &str[0] .

++ 17

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

:

charT* data() noexcept;

: p , p + i == &operator[](i) i [0, size()].

: .

: at p + size().

.data() .

.front():

const charT& front() const;

charT& front();

: !empty().

: operator[](0).

operator[]:

const_reference operator[](size_type pos) const;

reference operator[](size_type pos);

: pos <= size().

: *(begin() + pos) if pos < size(). charT charT(), undefined.

: .

: .

. . :

3 Basic_string - ([container.requirements.general]).

, :

, ([random.access.iterators]) iterator const_iterator ([iterator.requirements.general]).

:

, , n a (a + n), *(a + n) *(addressof(*a) + n), .

-, - ++ 17, ​​ papers.

:

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

, , , , , , , , . , , , , . , char*, , &str.front() &str[0] .

+15

&s[0] .

n , string ( ) n , , .

I.e., :

auto foo( int const n )
    -> string
{
    if( n <= 0 ) { return ""; }

    string result( n, '#' );   // # is an arbitrary fill character.
    int const n_stored = some_api_function( &result[0], n );
    assert( n_stored <= n );
    result.resize( n_stored );
    return result;
}

++ 11. , ++ 98 ++ 03, . ++ 98, - ndash; , ++ 11 ( , , 2005 ) , .


" ++ 17 data() std::string, , .

- , -const data(), , .


" , , .

, std::string.

- , .

0

, string, , , , ,
vector<char> vector<int> .

If it vis a vector, it ensures that it &v[0]points to sequential memory, which you can use as a buffer.

0
source

Source: https://habr.com/ru/post/1652811/


All Articles