2012-08-15 7 views
1

일부 포인터를 저장하기 위해 ptr_vector를 사용하려고하는데, 주된 방법으로 오류가 발생합니다.ptr_vector가 제대로 해제되지 않았습니다.

Critical error detected c0000374 
Windows has triggered a breakpoint in Path_Tree.exe. 

This may be due to a corruption of the heap, which indicates a bug in Path_Tree.exe or  any of the DLLs it has loaded. 

This may also be due to the user pressing F12 while Path_Tree.exe has focus. 

The output window may have more diagnostic information. 
The program '[7344] Path_Tree.exe: Native' has exited with code 0 (0x0). 

내가 잘못 뭐하는 거지 :

int main(void) 
{ 
    boost::ptr_vector<string> temp; 
    string s1 = "hi"; 
    string s2 = "hello"; 
    temp.push_back(&s1); 
    temp.push_back(&s2); 
    return 0; 
} 

이것은 내가 무엇입니까 오류 메시지가 : 여기 내 코드? 감사합니다.

답변

10

ptr_vector는 개체의 소유권이 (가 그들과 함께 수행 될 때 그 포인터에 delete를 호출하는 것을 의미한다) 당신이 그것에주는 포인터가 가리키는합니다. 당신은, 포인터의 단지 벡터를 원하는 경우에 사용하면 문자열의 단지 컨테이너를 원하는 경우

int main() 
{ 
    boost::ptr_vector<string> temp; 
    temp.push_back(new string("hi")); 
    temp.push_back(new string("hello")); 
    return 0; 
} 

:

int main() 
{ 
    std::vector<string*> temp; 
    //s1 and s2 manage their own lifetimes 
    //(and will be destructed at the end of the scope) 
    string s1 = "hi"; 
    string s2 = "hello"; 
    //temp[0] and temp[1] point to s1 and s2 respectively 
    temp.push_back(&s1); 
    temp.push_back(&s2); 
    return 0; 
} 

그렇지 않으면 결과 포인터와 push_back 다음 문자열이 새로운 사용하여 할당하고한다

int main() 
{ 
    std::vector<string> temp; 
    //s1 and s2 manage their own lifetimes 
    //(and will be destructed at the end of the scope) 
    string s1 = "hi"; 
    string s2 = "hello"; 
    //temp[0] and temp[1] refer to copies of s1 and s2. 
    //The vector manages the lifetimes of these copies, 
    //and will destroy them when it goes out of scope. 
    temp.push_back(s1); 
    temp.push_back(s2); 
    return 0; 
} 

ptr_vector

가 쉽게 값 의미를 가진 다형성 개체가 할 수 있도록하기위한 것입니다 : 일반적인 것은 문자열의 벡터가 될 것입니다. 문자열이 처음에 다형성이 아니라면 ptr_vector은 전혀 필요하지 않습니다.

+0

자세한 설명 주셔서 감사합니다! – Qman

1

ptr_vector은 동적으로 할당 된 객체에 대한 포인터를 저장하도록 설계되었습니다. 그런 다음 소유권을 가져 오며 수명이 끝나면 삭제합니다. 삭제할 수없는 객체에 포인터를 전달하면 정의되지 않은 동작이 발생합니다.

int main(void) 
{ 
    boost::ptr_vector<std::string> temp; 
    temp.push_back(new std::string("hi")); 
    temp.push_back(new std::string("hello")); 
    return 0; 
} 
+0

자동 정리를 수행하면 충돌이 발생하는 이유를 설명 할 수 있습니다. – Paranaix

+0

@Paranaix이 오류의 원인입니다. – juanchopanza

+0

이 코드를 작성하지 마십시오 (코드가 main에 완전히 포함되지 않은 일반적인 경우). 'new std :: string ("hello")'가 throw되면'new std :: string ("hi")'에 의해 생성 된 문자열은 삭제되지 않으며,'temp.push_back (s1)'이 던져지면 문자열 'new std :: string ("hello")'에 의해 생성 된 파일은 삭제되지 않습니다. – Mankarse

0

ptr_vector를 사용할 때 포인터를 다시 넣지 않아도됩니다.

std :: vector를 사용하거나 새 키워드로 할당 된 문자열을 푸시 백합니다.

관련 문제