일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
Tags
- 포토샵
- 수학
- CSS
- Prefix Sums
- 소수
- Gap
- grid
- skt membership
- 백준
- align-items
- Design Pattern
- pandas
- 확률
- 강화학습
- 에라토스테네스의 체
- 상태
- 통신사할인
- dataframe
- Flexbox
- c
- spring
- Javascript
- Codility
- c++
- SK바이오사이언스
- series
- 알고리즘
- margin
- Photoshop
- stl
Archives
- Today
- Total
sliver__
[Mastering C++ Programming] - shared_ptr 본문
728x90
- shared_ptr 스마트 포인터는 shared_ptr 개체 그룹이 힙 할당 개체의 소유권을 공유할 때 사용됩니다.
- shared_ptr 포인터는 모든 shared_ptr 인스턴스가 공유 개체 사용으로 완료되면 공유 개체를 해제합니다.
- shared_ptr 포인터는 참조 계산 메커니즘을 사용하여 공유 객체에 대한 총 참조를 확인합니다.
- 참조 횟수가 0이 될 때마다 마지막 shared_ptr 인스턴스가 공유 객체를 삭제합니다.
- 다음과 같은 예를 통해 shared_ptr의 사용을 확인해 보겠습니다.
#include <iostream>
#include <string>
#include <memory>
#include <sstream>
using namespace std;
class MyClass {
private:
static int count;
string name;
public:
MyClass() {
ostringstream stringStream(ostringstream::ate);
stringStream << "Object";
stringStream << ++count;
name = stringStream.str();
cout << "\nMyClass Default constructor - " << name << endl;
}
~MyClass() {
cout << "\nMyClass destructor - " << name << endl;
}
MyClass ( const MyClass &objectBeingCopied ) {
cout << "\nMyClass copy constructor" << endl;
}
MyClass& operator = ( const MyClass &objectBeingAssigned ) {
cout << "\nMyClass assignment operator" << endl;
}
void sayHello() {
cout << "Hello from MyClass " << name << endl;
}
};
int MyClass::count = 0;
int main ( ) {
shared_ptr<MyClass> ptr1( new MyClass() );
ptr1->sayHello();
cout << "\nUse count is " << ptr1.use_count() << endl;
{
shared_ptr<MyClass> ptr2( ptr1 );
ptr2->sayHello();
cout << "\nUse count is " << ptr2.use_count() << endl;
}
shared_ptr<MyClass> ptr3 = ptr1;
ptr3->sayHello();
cout << "\nUse count is " << ptr3.use_count() << endl;
return 0;
}
- 결과는 아래와 같습니다.
Hello from MyClass Object1
Use count is 1
Hello from MyClass Object1
Use count is 2
Hello from MyClass Object1
Use count is 2
MyClass destructor - Object1
728x90
'CS > C++' 카테고리의 다른 글
[Mastering C++ Programming] - Creating threads with the pthreads library (0) | 2022.12.08 |
---|---|
[Mastering C++ Programming] - weak_ptr / Circular dependency (0) | 2022.12.07 |
[Mastering C++ Programming] - unique_ptr (0) | 2022.12.07 |
[Mastering C++ Programming] - auto ptr (0) | 2022.12.07 |
[Mastering C++ Programming] - Smart Pointer (0) | 2022.12.07 |
Comments