sliver__

[Mastering C++ Programming] - unique_ptr 본문

CS/C++

[Mastering C++ Programming] - unique_ptr

sliver__ 2022. 12. 7. 21:59
728x90
  • unique_ptr 스마트 포인터는 auto_ptr과 정확히 동일한 방식으로 작동하지만 unique_ptr이 auto_ptr에 의해 도입된 문제를 해결한다는 점만 다릅니다. 
  • 따라서 unique_ptr은 C++11부터 auto_ptr을 대체합니다. 
  • unique_ptr 스마트 포인터를 사용하면 하나의 스마트 포인터만 힙 할당 개체를 독점적으로 소유할 수 있습니다. 
  • 한 unique_ptr 인스턴스에서 다른 인스턴스로의 소유권 이전은 std::move() 함수를 통해서만 수행할 수 있습니다.
  • 따라서 이전 예제를 리팩토링하여 auto_ptr 대신 unique_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 << "\nHello from MyClass" << endl;
          }

};

int MyClass::count = 0;

int main ( ) {

 unique_ptr<MyClass> ptr1( new MyClass() );
 unique_ptr<MyClass> ptr2( new MyClass() );

 ptr1->sayHello();
 ptr2->sayHello();

 //At this point the below stuffs happen
 //1. ptr2 smart pointer has given up ownership of MyClass Object 2
 //2. MyClass Object 2 will be destructed as ptr2 has given up its 
 // ownership on Object 2
 //3. Ownership of Object 1 will be transferred to ptr2
 ptr2 = move( ptr1 );

 //The line below if uncommented will result in core dump as ptr1 
 //has given up its ownership on Object 1 and the ownership of 
 //Object 1 is transferred to ptr2.
 // ptr1->sayHello();

 ptr2->sayHello();
 
 return 0;
}

 

  • 결과는 아래와 같습니다.
./a.out

MyClass Default constructor - Object1

MyClass Default constructor - Object2

Hello from MyClass

Hello from MyClass

MyClass destructor - Object2

Hello from MyClass

MyClass destructor - Object1
728x90
Comments