Reading source byte array in std :: string

I wondered about the following problem: suppose I have a C-style function that reads raw data into a buffer

int recv_n(int handle, void* buf, size_t len); 

Can I read data directly in std:string or stringstream without allocating temporary buffers? For instance,

 std::string s(100, '\0'); recv_n(handle, s.data(), 100); 

I think this solution has the result undefined, because afaik, string::c_str and string::data can return a temporary location and do not have to return a pointer to the real place in memory used by the object to store the data.

Any ideas?

+4
source share
2 answers

Why not use vector<char> instead of string ? That way you can:

 vector<char> v(100, '\0'); recv_n(handle, &v[0], 100); 

This seems more idiomatic to me, especially since you are not using it as a string (you say that this is raw data).

+10
source

Yes, after C ++ 11.

But you cannot use s.data() as it returns char const*

Try:

 std::string s(100, '\0'); recv_n(handle, &s[0], 100); 

Depending on the situation, I could choose std :: vector <char> especially for raw data (although all this will depend on the use of data in your application).

+7
source

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


All Articles