잘 알지도 못하면서 헤딩했다가 피를 보고 나서 제대로 공부해야겠다고 생각하여 따로 포스트를 작성한다.
먼저 훗날 까먹을 지도 모르는 나를 위해 기본적인 걸 적고 간다.
스마트 포인터를 사용하기 위해서는 <memory> 헤더 파일을 인클루드 해야한다.
네임스페이스 std를 사용한다.
먼저 shared_ptr에 대해서이다.
class Something {
int a;
public:
~Something() {
cout << "Heros never DIE!" << endl;
}
};
void Foo(vector<shared_ptr<Something>>& v)
{
cout << "Foo Calling!" << endl;
shared_ptr<Something> sp(new Something);
v.push_back(sp);
}
int main()
{
vector<shared_ptr<Something>> v;
Foo(v);
cout << "Foo Ends!" << endl;
v.erase(v.begin());
cout << "erase complete!" << endl;
while (1);
}
이렇게 놓고 실행하면 제대로 소멸자가 호출된다.
순서를 살펴보면 Foo함수 호출시에 shared_ptr(sp)을 선언함 -> useCount +1
벡터에 넣어줌 -> useCount +1
Foo 함수가 끝나면서 지역변수였던 sp가 사라짐 -> useCount -1
vector에서 erase를 해줌 -> useCount -1
그래서 총 useCount가 0이 되면서 삭제가 되는 것.
신기한 점은 vector에 들어갈 때 포인터나 레퍼런스를 넣은 것이 아닌데도 불구하고 객체가 사라지지 않았다는 점이다.
어떻게 구현한 거지?
어쨌든 use_count()함수를 가지고 레퍼런스 카운팅을 해보면 다음과 같은 결과가 나온다.
class Something {
int a;
public:
~Something() {
cout << "Heros never DIE!" << endl;
}
};
void Foo(vector<shared_ptr<Something>>& v)
{
cout << "Foo Calling!" << endl;
shared_ptr<Something> sp(new Something);
cout << sp.use_count() << endl; //1
v.push_back(sp);
cout << v[0].use_count() << endl; //2
cout << sp.use_count() << endl;
}
int main()
{
vector<shared_ptr<Something>> v;
Foo(v);
cout << "Foo Ends!" << endl;
cout << v[0].use_count() << endl; //1
v.erase(v.begin());
//0
cout << "erase complete!" << endl;
while (1);
}
'Programming' 카테고리의 다른 글
| C++에서 C# Style Property 사용하기 (1) | 2019.12.18 |
|---|---|
| 멀티쓰레딩 연습 (0) | 2019.12.18 |
| Enum class 에 대한 한가지 사실 (0) | 2019.12.16 |
| MonsterWorld 1 (콘솔 2차원 게임) 과제 (1) | 2018.10.25 |
| C++ 콘솔창 1차원 게임 과제 (0) | 2018.10.25 |