Directly write into char* buffer of std::string

后端 未结 3 887
失恋的感觉
失恋的感觉 2021-02-05 23:28

So I have an std::string and have a function which takes char* and writes into it. Since std::string::c_str() and std::string::data(

3条回答
  •  时光取名叫无心
    2021-02-06 00:15

    You can simply use &s[0] for a non-empty string. This gives you a pointer to the start of the buffer

    When you use it to put a string of n characters there the string's length (not just the capacity) needs to be at least n beforehand, because there's no way to adjust it up without clobbering the data.

    I.e., usage can go like this:

    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;
    }
    

    This approach has worked formally since C++11. Before that, in C++98 and C++03, the buffer was not formally guaranteed to be contiguous. However, for the in-practice the approach has worked since C++98, the first standard – the reason that the contiguous buffer requirement could be adopted in C++11 (it was added in the Lillehammer meeting, I think that was 2005) was that there were no extant standard library implementations with a non-contiguous string buffer.


    Regarding

    C++17 added added non-const data() to std::string but it still says that you can't modify the buffer.

    I'm not aware of any such wording, and since that would defeat the purpose of non-const data() I doubt that this statement is correct.


    Regarding

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

    If copying the buffer has a noticeable impact, then you'd want to avoid inadvertently copying the std::string.

    One way is to wrap it in a class that's not copyable.

提交回复
热议问题