[C++11 Overview] make_shared

Book Review 2013. 4. 26. 15:41

make_shared<T>(...) 는 T 의 생성자에서 요구하는 파라미터 값들을 인자로 주고

shared_ptr 객체를 얻습니다. 이 때, 표준상에서 구현이 강제되어 있지는 않지만

보통 make_shared 구현에서는  T 타입 객체에 대한 포인터와 참조카운트를 관리하는 객체의

메모리 할당을 하나의 메모리 블럭에 할당하는데, shared_ptr 객체를 직접 생성할 경우

두 군데의 다른 메모리 블럭으로 나뉘어지는 것에 비해 성능상 이득이 있다고 하네요.


cppreference 의 다음 글을 참조해보면 되겠습니다.


http://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared


This function typically allocates memory for the T object and for the shared_ptr's control block with a single memory allocation (it is a non-binding requirement in the Standard). In contrast, the declaration std::shared_ptr<T> p(new T(Args...)) performs at least two memory allocations, which may incur unnecessary overhead.

Moreover, f(shared_ptr<int>(new int(42)), g()) can lead to memory leak if g throws an exception. This problem doesn't exist if make_shared is used.


: