我是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