是否可以直接保留并复制到std::string中?

Is it possible to reserve and copy into a std::string directly?

是否可以在 std::string 中保留 space 并获取指针以将 char 数据直接复制到其中? 我必须通过将 returns 字符串复制到 char * 中来与 C 库进行交互。 我如何设置 std::string 以便库可以直接写入其中,避免中间副本。

假设示例:

std::string mystring;
int strlen = foolib_get_string_size(fooval);
mystring.size(strlen); // assuming size() with arg exists and does reserve() and set size
foolib_string_to_char_buffer(fooval, mystring.data(), strlen); // abusing data() method for writing

Is it possible to reserve space in a std::string and get a pointer to copy char data directly into it?

是的。使用其 resize() 方法分配内存,然后使用其 data() 方法(C++17 及更高版本)或其 operator[] 来访问该内存。

I have to interface with a C library that returns strings by copying them into a char *. How can I set up a std::string so that the library can write directly into it, avoiding intermediate copies.

像这样:

std::string mystring;
int strlen = foolib_get_string_size(fooval);
if (strlen > 0)
{
    mystring.resize(strlen); // -1 if strlen includes space for a null terminator
    foolib_string_to_char_buffer(fooval, mystring.data()/*&mystring[0]*/, strlen);
}

或者,std::string 也有可以分配内存的构造函数:

int strlen = foolib_get_string_size(fooval);
std::string mystring(strlen, '[=11=]'); // -1 if strlen includes space for a null terminator
if (strlen > 0)
    foolib_string_to_char_buffer(fooval, mystring.data()/*&mystring[0]*/, strlen);

当然,这确实需要连续分配std::string的内存块,这仅在C++11及更高版本中得到保证(但在实践中, 几乎在所有已知的实现中都完成了)。如果您不使用 C++11 或更高版本,并且真的想符合标准,那么您应该使用中间缓冲区,例如 std::vector,例如:

std::string mystring;
int strlen = foolib_get_string_size(fooval);
if (strlen > 0)
{
    std::vector<char> myvector(strlen);
    foolib_string_to_char_buffer(fooval, &myvec[0], strlen);
    mystring.assign(&myvec[0], strlen); // -1 if strlen includes space for a null terminator
}