내 문자열 조작에 std :: string 유형을 사용하고 있습니다.C++ : std :: string 개체에서 char * 포인터를 분리 할 수 있습니까?
그러나 원래 std :: string 개체가 삭제 된 후에도 원시 char * 포인터를 유지해야하는 경우가 있습니다 (예, char * 포인터가 HEAP를 참조하므로 결국 처분해야 함).
그러나 원시 포인터를 문자열에서 분리 할 방법이없는 것처럼 보입니까?
아마 다른 문자열 구현을 사용해야합니까?
감사합니다.
편집
사람들은, 복사와 분리 혼동하지 마십시오. 분리의 핵심은 문자열 객체가 기본 버퍼에 대한 소유권을 포기하는 것입니다.
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
원래 개체를 삭제하면'c_str'도 사라집니다. 그리고 C++ 11의 FWIW는'data'와'c_str' 둘 다 내부 버퍼를 가리키는 널 종료 문자열을 반환합니다. –