2. shared_ptr
- 하나의 객체를 참조하는 스마트 포인터의 갯수를 참조하는 스마트 포인터
- 참조 횟수(reference count) : 새로운 shared_ptr 추가시 1증가, 제거시 1감소
- 참조 횟수가 0이 되면 메모리를 자동으로 해제
사용법
#include<memory> 추가
shared_ptr<객체>스마트 포인터 명(new 객체);
shared_ptr<객체>스마트 포인터 명 = make_shared<객체>(인수);
shared_ptr 객체 Lee를
sharedLee로 참조하여 레퍼런스 카운터가 2가 되었고
Lee를 해제시 sharedLee가 같은 값을 참조하고 있으므로 데이터는 삭제되지않고
러퍼런스 카운터만 1 줄어든다.
총 코드
#include<iostream>
#include<memory>
#include<string>
using namespace std;
class Person
{
string name;
int age;
public:
Person(const string& name, int age);
~Person();
void ShowData();
};
Person::Person(const string& name, int age)
{
this->age = age;
this->name = name;
cout << "Person 생성자 생성" << endl;
}
Person::~Person()
{
cout << "Person 소멸자 생성" << endl;
}
void Person::ShowData()
{
cout << "나이 : " << age << endl;
cout << "이름 : " << name << endl;
}
int main()
{
shared_ptr<Person> Lee(new Person("JaeWoo", 31));
Lee->ShowData();
cout << "reference count : " << Lee.use_count() << endl;
auto sharedLee(Lee);
cout << "reference count : " << Lee.use_count() << endl;
Lee.reset();
cout << "reference count : " << sharedLee.use_count() << endl;
shared_ptr<Person> Lee2 = make_shared<Person>("JaeWoo", 31);
Lee2->ShowData();
cout << "reference count : " << Lee2.use_count() << endl;
auto sharedLee2(Lee2);
cout << "reference count : " << Lee2.use_count() << endl;
sharedLee2.reset();
cout << "reference count : " << Lee2.use_count() << endl;
}
'프로그래밍 공부 > modern C++' 카테고리의 다른 글
modern C++ 범위 기반 for문 (rage-based for statement) (0) | 2022.02.18 |
---|---|
auto (0) | 2022.02.17 |
스마트 포인터 weak_ptr (0) | 2022.02.17 |
스마트 포인터란? && unique_ptr (0) | 2022.02.13 |
Modern C++ 이란? (0) | 2022.02.12 |