I came across this way of using a std::string to receive a buffer.
Here it is simplified:
error_enum_t get_fn(char*, unsigned long, unsigned long*);
void getStringValuedAttribute(std::string &value)
{
if (value.size() == 0) {
value.resize(32);
}
unsigned long actual_size;
get_fn(&value[0], value.size(), &actual_size));
if (actual_size >= value.size()) {
value.resize(actual_size + 1);
get_fn(&value[0], value.size(), &actual_size);
}
}
After some digging on repl.it, I see that &value[0]
is type char *
, which I guess makes sense, because value[0]
would have to be char
. But it seems like this is giving direct access to value
's buffer. Is that all that is going on here, or is there more wizardry afoot?
I tried digging into the source of basic_string.h
and I see _M_local_buf
, but there is a ton of template action going on and this is not my strong suit.
If I had to wager a guess, value[]
is leveraging operator []
overloading to get access to a pointer reference to the start of the internal buffer, which is compatible with char *
, so the get_fn
is able to treat it like a vanilla buffer.
Is my assessment correct? Is this a wise idiom, nay, is it even safe?