엔지니어 동행하기

Smart Pointer 설명과 예제 본문

Modern C++/Smart Pointer

Smart Pointer 설명과 예제

엔지니어 설리번 2022. 6. 5. 11:14
반응형
C++ 은 Memory(RAM)을 개발자가 직접 관리할 수있는 HW와 매우 밀접한 언어입니다. 그렇기 때문에 더욱 빠른 코드를 작성할 수 있지만, 잘못 사용할 경우 Segmentation fault, Memory Leak과 같은 문제가 발생할 수 있습니다. 따라서 Smart Pointer를 적절히 사용할 수 있어야 합니다.

 

Smart Pointer 사용 이유

RAII ( Resource Acquisition Is Initailization) : Resource의 life cycle과 Object의 life cycle을 일치시켜 Memory Leak을 원천적으로 방지하기 위함

- Resource : Heap memory, Thread, Mutex, File access, DB connection 등이 이에 해당

- Object : Smart Pointer

(여기서 Heap mormry와 Smart Pointer의 경우를 예로 설명드리겠습니다. )

 

C++ Style의 Heap memory 사용 방법

void my_func()
{
    int* valuePtr = new int(15);
    int x = 45;
    // ...
    if (x == 45)
        return;   // here we have a memory leak, valuePtr is not deleted
    // ...
    delete valuePtr;
}
 
int main()
{
	my_func();
}

Smart pointer를 사용하지 않은 기존 방식은 new, delete keyword를 사용해 Heap memory 할당, 해제하여 사용하였습니다. 위의 코드에서 delete를 통해 메모리 해제 하기 전에, x == 45인 조건이 만족하여 return 해버리면 Memory Leak이 발생합니다. 

▶   해당 Process의 memory 사용률 (%MEM)이 증가하고, 프로그램이 죽거나, 이상 동작하게 됩니다.

 

Safer C++ Style

#include <memory>
 
void my_func()
{
    std::unique_ptr<int> valuePtr(new int(15));
    int x = 45;
    // ...
    if (x == 45)
        return;   // no memory leak anymore!
    // ...
}
 
int main()
{
	my_func();
}

Smart pointer 중 std::unique_ptr를 사용하여 Heap memory를 할당하였습니다. 해당 포인터는 Scoped based를 동작하여 my_func 이라는 scope가 끝날 때(return 시), 할당된 메모리를 자동으로 해제합니다. 

▶ 이러한 방식으로 Memory leak을 원천적으로 방지합니다.


 

smart pointers - cppreference.com

Warning: This wiki is part of the deprecated and unmaintained CppReference Book project. For up-to-date information on C++, see the main reference at cppreference.com. Smart pointers are used to make sure that an object is deleted if it is no longer used (

en.cppreference.com

  • std::unique_ptr
  • std::shared_ptr
  • std::weak_ptr
  • std::auto_ptr
반응형

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

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