我使用std :: string类型进行字符串操作.
但是,有时我需要保留原始的char*指针,即使在原始的std :: string对象被销毁之后(是的,我知道char*指针引用了HEAP并且最终必须被处理掉).
但是,看起来没有办法从字符串中分离原始指针或者是吗?
也许我应该使用另一个字符串实现?
谢谢.
编辑
伙计们,请不要将分离与复制混淆.分离的本质是字符串对象放弃其对底层缓冲区的所有权.所以,如果字符串有detach方法,它的语义将是这样的:
char *ptr = NULL;
{
std::string s = "Hello world!";
ptr = s.detach(); // May actually allocate memory, if the string is small enough to have been held inside the static buffer found in std::string.
assert(s == NULL);
}
// at this point s is destroyed
// ptr continues to point to a valid HEAP memory with the "Hello world!" string in it.
...
delete ptr; // need to cleanup
Run Code Online (Sandbox Code Playgroud)
不,不可能分离返回的指针std::string::c_str().
解决方案:创建字符串的只读副本,并确保该副本至少与您需要char*指针一样长.然后c_str()在该副本上使用,只要您愿意,它就会有效.
如果那是不可能的,那么你将无法释放它们char*.任何将指针包装在RAII结构中的尝试都只会重新发明std :: string的部分内容.