🎯 오늘 목표
void func(){
int a= 10;
}
a는
but
int* createValue(){
int a = 10;
return &a; // x
}
int* p = new int(10);
자동삭제는 X
int *p =new int(10);
delete p;
=> 이 메모리는 이제 필요없다를 명시적으로 선언
while(true)
{
int *p = new int(10);
}
=> 메모리 누수
=> 프로그램은 조용히 죽어감
int *p = new int(10);
func(p);
- func가 delete?
- main이 delete?
int*p = new int(10);
throw;
delete p; // 실행 안됨
delete p;
delete p;
RALL : 자원의 생명주기를 객체의 생명주기에 묶자
이전
int*p = new int(10);
// ...
delete p;
현대
#include <memory>
auto p = std::make_unique<int>(10);
unique_ptr : 단독소유 : 사용처 기본
shared_ptr : 공동소유 : 사용처 제한적
weak_ptr : 감시용 : 사용처 순환참조방지
std::unique_ptr<int> p = std::make_unique<int>(10);
이동ex)
auto p1 = std::make_unique<int>(10);
auto p2 = std::move(p1);
p1->nullptr
p2->메모리
auto p1 = std::make_shared<int>(10);
auto p2 = p1;
std::weak_ptr<int> wp = sp;
CreateThread(
nullptr,
0,
ThreadFunc,
this, // 포인터
0,
nullptr
RAII : Resource Acquisition Is Initialization