【发布时间】:2012-01-02 09:29:17
【问题描述】:
我正在使用 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
【问题讨论】: