std :: unique_ptr을 선언하는 방법과 그 용도는 무엇입니까?
나는 방법을 이해하려고 std::unique_ptr
일을하고 내가 발견 이 문서를. 작성자는 다음 예제에서 시작합니다.
#include <utility> //declarations of unique_ptr
using std::unique_ptr;
// default construction
unique_ptr<int> up; //creates an empty object
// initialize with an argument
unique_ptr<int> uptr (new int(3));
double *pd= new double;
unique_ptr<double> uptr2 (pd);
// overloaded * and ->
*uptr2 = 23.5;
unique_ptr<std::string> ups (new std::string("hello"));
int len=ups->size();
나에게 헷갈리는 것은이 줄에서
unique_ptr<int> uptr (new int(3));
정수를 인수로 사용합니다 (반올림 괄호 사이).
unique_ptr<double> uptr2 (pd);
포인터를 인수로 사용했습니다. 차이가 있습니까?
나에게도 명확하지 않은 것은 이러한 방식으로 선언 된 포인터가 "정상적인"방식으로 선언 된 포인터와 어떻게 다른지입니다.
의 생성자는 unique_ptr<T>
유형의 객체에 대한 원시 포인터를 T
허용하므로을 허용합니다 T*
.
첫 번째 예에서 :
unique_ptr<int> uptr (new int(3));
포인터는 new
표현식 의 결과이며 두 번째 예에서는 다음과 같습니다.
unique_ptr<double> uptr2 (pd);
포인터는 pd
변수에 저장됩니다 .
개념적으로는 아무것도 변경되지 않지만 ( unique_ptr
원시 포인터에서를 생성하고 있음) 두 번째 방법은 예를 들어 다음을 수행 할 수 있으므로 잠재적으로 더 위험합니다.
unique_ptr<double> uptr2 (pd);
// ...
unique_ptr<double> uptr3 (pd);
따라서 동일한 객체를 효과적으로 캡슐화하는 두 개의 고유 포인터가 있습니다 (따라서 고유 포인터 의 의미를 위반 함 ).
이것이 가능한 경우 고유 포인터를 만드는 첫 번째 양식이 더 나은 이유입니다. C ++ 14에서는 다음을 수행 할 수 있습니다.
unique_ptr<int> p = make_unique<int>(42);
더 명확하고 안전합니다. 이제 당신의 의심에 대해 :
나에게도 명확하지 않은 것은 이러한 방식으로 선언 된 포인터가 "정상적인"방식으로 선언 된 포인터와 어떻게 다른지입니다.
스마트 포인터는 개체 소유권을 모델링해야하며 해당 개체에 대한 마지막 (스마트, 소유) 포인터가 범위를 벗어날 때 지적 된 개체를 자동으로 파괴합니다.
이렇게하면 delete
동적으로 할당 된 객체 에 대해 수행하는 것을 기억할 필요가 없습니다 . 스마트 포인터의 소멸자가 자동으로 수행 할 것입니다. 이미 소멸 된 객체에 대한 (매달린) 포인터를 역 참조하지 않을 것인지에 대해 걱정할 필요가 없습니다.
{
unique_ptr<int> p = make_unique<int>(42);
// Going out of scope...
}
// I did not leak my integer here! The destructor of unique_ptr called delete
이제는 unique_ptr
고유 한 소유권을 모델링하는 스마트 포인터입니다. 즉, 프로그램에서 언제든지 뾰족한 개체에 대한 하나의 (소유) 포인터 만있을 것 unique_ptr
입니다. 이것이 복사 할 수없는 이유 입니다.
준수해야하는 암시 적 계약을 위반하지 않는 방식으로 스마트 포인터를 사용하는 한, 메모리가 유출되지 않고 객체에 대한 적절한 소유권 정책이 적용된다는 보장을 받게됩니다. 원시 포인터는 이러한 보장을 제공하지 않습니다.
unique_ptr에 할당하는 두 개념에는 차이가 없습니다.
int* intPtr = new int(3);
unique_ptr<int> uptr (intPtr);
~와 비슷하다
unique_ptr<int> uptr (new int(3));
여기서 unique_ptr 은에서 차지하는 공간을 자동으로 삭제합니다 uptr
.
이런 식으로 선언 된 포인터가 "정상적인"방식으로 선언 된 포인터와 어떻게 다른지.
힙 공간에 정수를 생성하는 경우 ( new keyword 또는 malloc 사용 ), 해당 메모리를 직접 삭제 해야합니다 ( 각각 delete 또는 free 사용 ).
아래 코드에서
int* heapInt = new int(5);//initialize int in heap memory
.
.//use heapInt
.
delete heapInt;
Here, you will have to delete heapInt, when it is done using. If it is not deleted, then memory leakage occurs.
In order to avoid such memory leaks unique_ptr is used, where unique_ptr automatically deletes the space occupied by heapInt when it goes out of scope.
Unique pointers are guaranteed to destroy the object they manage when they go out of scope. http://en.cppreference.com/w/cpp/memory/unique_ptr
In this case:
unique_ptr<double> uptr2 (pd);
pd
will be destroyed when uptr2
goes out of scope. This facilitates memory management by automatic deletion.
The case of unique_ptr<int> uptr (new int(3));
is not different, except that the raw pointer is not assigned to any variable here.
참고URL : https://stackoverflow.com/questions/16894400/how-to-declare-stdunique-ptr-and-what-is-the-use-of-it
'Program Tip' 카테고리의 다른 글
JavaScript를 사용하여 Safari에서 키보드 이벤트 실행 (0) | 2020.10.27 |
---|---|
Heroku 서버 상태 이해 143 (0) | 2020.10.27 |
메소드 참조 캐싱이 Java 8에서 좋은 아이디어입니까? (0) | 2020.10.27 |
Android에서 Git을 사용하는 방법? (0) | 2020.10.27 |
IE8 브라우저 모드와 문서 모드 (0) | 2020.10.27 |