엔지니어 동행하기

std::unique_ptr 설명과 예제 본문

Modern C++/Smart Pointer

std::unique_ptr 설명과 예제

엔지니어 설리번 2022. 6. 5. 16:30
반응형
Smart Pointer는 RAII idiom 기법을 따르며, C++에서 메모리 관리를 위한 핵심 개념입니다. 그중 첫 번째로 Exclusive ownership을 보장하는 std::unique_ptr에 대해 다뤄보겠습니다. 

 

Exclusive Ownership

(Heap memory 상의) 하나의 Object는 하나의 Pointer만 가리킬 수 있음을 의미합니다. 

#include <iostream>
#include <memory>

struct D
{
    D() { std::cout << "D::D\n"; }
    ~D() { std::cout << "D::~D\n"; }
    void bar() { std::cout << "D::bar\n"; }
};

int main()
{
    // Create a (uniquely owned) resource
    std::unique_ptr<D> p = std::make_unique<D>();
    std::unique_ptr<D> p2 = p;  //Compile error, D Object를 두 개의 pointer가 가리키도록 허용하지 않음
}

위의 코드에서 main frame stack에 생성된 smart pointer 객체인 p는 Heap memory의 D object를 가리킵니다. 

std::unique_ptr<D> p2 = p;  코드의 의도는 copy assignment 를 통해 smart point객체인 p2 또한 D object를 가리키도록 하는 것인데, 이를 허용하지 않기 때문에 Compile error가 발생합니다. (즉 Copy를 지원하지 않습니다.)

Copy는 안되지만, Move는 가능합니다. 즉 Object D에 대한 소유권을 p2에게 넘겨줄 수 있습니다.

int main()
{
    // Create a (uniquely owned) resource
    std::unique_ptr<D> p = std::make_unique<D>();
    std::unique_ptr<D> p2 = std::move(p);
}

▶  따라서 개발자는 소유권에 대한 고려를 하지 않아도 됩니다.

 

std::unique_ptr를 사용하는 경우 (중요)

Dynamic Polymorphism을 구현하기 위해, Class의 member variable로 pointer를 가져야 하는 경우에 사용합니다. 

member pointer가 가리키는 object를 다른 pointer가 가리키지 않는 것을 보장해서, 개발자가 Object life cycle을 고려하지 않아도 됩니다.

▶ 개발자가 Rule of three를 고려하지 않아도 됩니다.


 

std::unique_ptr - cppreference.com

(1) (since C++11) template <     class T,     class Deleter > class unique_ptr ; (2) (since C++11) std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of sco

en.cppreference.com

반응형

'Modern C++ > Smart Pointer' 카테고리의 다른 글

std::shared_ptr 설명과 예제  (0) 2022.06.06
Smart Pointer 설명과 예제  (0) 2022.06.05
Comments