sliver__

[Mastering C++ Programming] - shared_ptr 본문

CS/C++

[Mastering C++ Programming] - shared_ptr

sliver__ 2022. 12. 7. 22:03
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
Comments