我是C++新手。我假定std::string
使用引用计数来确定何时释放缓冲区。在以下示例中,当f()
返回时,s
缓冲区将被释放。如果我想将字符串缓冲区的所有权授予give_ownership_of
而不是释放它?我可以从C++中的std :: string分离缓冲区吗?
void f()
{
string s = read_str();
give_ownership_of(s);
}
UPDATE
让我补充更多的细节到的问题。实际的代码看起来是这样,
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);
}
一些实现**在内部使用引用计数机制。它是否引起你的问题? –
你有什么特别的理由想要获得内部'char *'缓冲区的所有权,而不是传递'std :: string'对象吗? – LihO
我不确定这可以做到吗? – james82345