我是 C++ 新手。我假设std::string
使用引用计数来确定何时释放缓冲区。在下面的示例中,s
缓冲区将在f()
返回时被释放。如果我想将字符串缓冲区的所有权授予give_ownership_of
而不是释放它怎么办?
void f()
{
string s = read_str();
give_ownership_of(s);
}
更新
让我在问题中添加更多细节。实际代码如下所示,
string read_str();
void write_str_async(const char *str, void (*free_fn)(const char*));
void f() {
string s = read_str();
// write_str_async() need to access the buffer of s after f() returns.
// So I'm responsible to keep s alive until write_str_async() calls free_fn to release the buffer when the write is done.
// The PROBLEM here is that s will be released when the variable scope ends. NOTE: I'm not able to change either read_str() or write_str_async() here.
write_str_async(s.c_str(), my_free_fn);
}