Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 |
Tags
- tcp
- Close
- mutex
- Sync
- JavaScript
- c++
- range
- window
- channel
- FOR
- windows
- write
- bitcoin
- GO 언어
- install
- 책
- 영화
- Callback
- Python
- go
- http
- json
- API
- File
- package
- 리뷰
- Golang
- C
- go언어
- Linux
Archives
- Today
- Total
Code Habit
[c++] 스마트 포인터 ( shared_ptr, weak_ptr, unique_ptr ) 본문
스마트 포인터는 c++에서 메모리 관리를 자동화하고 안전하게 처리하기 위한 포인터 유형이다. 스마트 포인터는 메모리 누수와 댓글 포인터( 포인터가 가리키는 메모리가 해제된 후에도 그 주소를 참조하는 문제 ) 방지해준다.
1. std::shared_ptr
- reference count를 사용하여 특정 메모리를 참조하는 포인터의 개수를 관리하며 count가 0이 되면 자동으로 메모리를 해제하여 메모리 누수를 방지한다.
#include <iostream>
#include <memory>
int main() {
std::shared_ptr<int> ptr1 = std::make_shared<int>(42); // ref 1
std::shared_ptr<int> ptr2 = ptr1; // ref 2
std::cout << "shared count" << ptr1.use_count() << std::endl; // 2
std::cout << "shared count" << ptr2.use_count() << std::endl; // 2
}
2. std::weak_ptr
- shared_ptr과 함께 사용되며 하나 이상의 shared_ptr이 가리키는 메모리를 참조할 수 있으나 reference count를 늘리지 않는 스마트 포인터이다. weak_ptr을 사용하면 shared_ptr이 서로를 가리키며 해제되지 않는 순환참조를 방지할 수 있다.
#include <iostream>
#include <memory>
int main() {
std::shared_ptr<int> ptr1 = make_shared<int>(3); // ref 1
std::weak_ptr<int> ptr2 = ptr1; // ref 1
std::cout << "reference count : " << ptr1.use_count() << std::endl; // 1
}
3. std::unique_ptr
- 하나의 포인터만 객체를 가리킬 수 있다. reference count는 1을 넘기지 않는다.
#include <iostream>
#include <memory>
int main() {
std::unique_ptr<int> ptr1 = std::make_unique<int>(3);
std::unique_ptr<int> ptr2 = ptr1; // 컴파일 오류, 참조 불가
std::unique_ptr<int> ptr2 = std::move(ptr1); // ptr1 -> ptr2 소유권 이전
return 0;
}