Done/C++_Python
[C++] Smart Pointer (Unique pointer, shared pointer) [1]
weasel7
2023. 9. 2. 09:01
728x90
본 글의 내용은 여러 글과 영상을 바탕으로 제가 이해하기 위해 재구성된 글입니다. 내용에 오류가 있으면 댓글 부탁드리고, 저작권적으로 문제가 된다면 비공개 or 삭제 조치 취하겠습니다
먼저 SmartPtr은 c++에서 자주(?) 발생하는 memory leak의 원천 방지를 하는 역할을 함
우리가 new를 통해 heap 공간에 있는 객체를 바라보는 stack 공간의 변수를 생성해주고 delete를 하지 않으면 stack공간에서 heap공간을 가르키는 녀석은 scope 내에서 사라지지만 heap 공간 자체에서 생성된 메모리를 차지하는 녀석은 사라지지 못한다!!!
그래서 이를 지워주기 위해 delete를 해야하지만!!~!!!!! 우리는 가끔 그것을 까먹을 가능성이 있다 => 이를 해결하고자 등장한게 스마트 포인터!!!!
Smart Pointer의 종류
- unique pointer
- shared pointer
=> 본 종류들은 object 와 resource(heap memory, thread, file access, mutex, db comention)간의 라이프 사이클을 일치시키는 역할을 함
unique_ptr
- scope based 의 pointer로 써 scope를 벗어나면 사라짐
#include <iostream>
#include <memory>
using namespace std;
class Cat{
public:
explicit Cat(int age):mAge{age}
{
std::cout << "cat constructor"<< std::endl;
}
~Cat() noexcept
{
std::cout << "cat destructor" << std::endl;
}
private:
int mAge;
};
void foo()
{
std::cout << "foo in" <<std::endl;
std::unique_ptr<Cat> catPtr = std::make_unique<Cat>(3);
std::cout << "foo out" << std::endl;
}
int main()
{
std::cout<<"before scope" << std::endl;
foo();
std::cout <<"after"<<std::endl;
return 0;
}
728x90