다음을 통해 공유


make_shared(<memory>)

기본 할당자를 사용하여 하나 이상의 인수에서 작성된 할당된 개체를 가리키는 shared_ptr를 만들고 반환합니다. 지정된 형식의 개체와 shared_ptr을 모두 할당 및 생성하여 개체의 공유 소유권을 관리하고 shared_ptr을 반환합니다.

template<class Type, class... Types>     shared_ptr<Type> make_shared(         Types&&... _Args     );

매개 변수

매개 변수

설명

_Args

0개 이상의 생성자 인수입니다. 이 함수는 제공되는 인수에 따라 호출할 생성자 오버로드를 유추합니다.

속성 값/반환 값

할당 및 생성된 개체를 가리키는 shared_ptr을 반환합니다.

설명

make_shared를 개체 및 shared_ptr을 만드는 간단하고 보다 효율적인 방법으로 사용하여 개체에 대한 공유 액세스를 동시에 관리할 수 있습니다. 의미상으로 다음 두 문은 동일합니다.

   auto sp = std::shared_ptr<Example>(new Example(argument));
   auto msp = std::make_shared<Example>(argument);

그러나 첫 번째 문은 두 개의 할당을 만들고, Example 개체의 할당이 성공한 후에 shared_ptr의 할당이 실패하면 명명되지 않은 Example 개체가 유출됩니다. make_shared를 사용하는 문은 관련된 함수 호출이 하나뿐이므로 더 간단합니다. 라이브러리가 개체와 스마트 포인터에 대해 단일 할당을 만들 수 있으므로 더 효율적입니다. 또한 더 빠르면서 메모리 조각화를 덜 유발하며, 둘 중 하나의 할당에서만 예외가 발생할 가능성이 없습니다. 개체를 참조하고 스마트 포인터의 참조 카운트를 업데이트하는 코드에 대한 집약성이 더 높아지므로 성능이 향상됩니다.

개체에 대한 공유 액세스가 필요하지 않은 경우에는 make_unique 사용을 고려하세요. 개체에 대한 사용자 지정 할당자를 지정해야 하는 경우에는 allocate_shared를 사용합니다. deleter를 인수로 전달할 수 있는 방법이 없으므로 개체에 사용자 지정 deleter가 필요한 경우 make_shared를 사용할 수 없습니다.

다음 예에서는 특정 생성자 오버로드를 호출하여 형식에 대한 공유 포인터를 만드는 방법을 보여 줍니다.

예제

// stl_make_shared.cpp
// Compile by using: cl /W4 /EHsc stl_make_shared.cpp
#include <iostream>
#include <string>
#include <memory>
#include <vector>

class Song {
public:
   std::wstring title_;
   std::wstring artist_;

   Song(std::wstring title, std::wstring artist) : title_(title), artist_(artist) {}
   Song(std::wstring title) : title_(title), artist_(L"Unknown") {}
};

void CreateSharedPointers() {
   // Okay, but less efficient to have separate allocations for
   // Song object and shared_ptr control block.  
   auto song = new Song(L"Ode to Joy", L"Beethoven");
   std::shared_ptr<Song> sp0(song);

   // Use make_shared function when possible. Memory for control block
   // and Song object are allocated in the same call:  
   auto sp1 = std::make_shared<Song>(L"Yesterday", L"The Beatles");
   auto sp2 = std::make_shared<Song>(L"Blackbird", L"The Beatles");
   
   // make_shared infers which constructor to use based on the arguments.
   auto sp3 = std::make_shared<Song>(L"Greensleeves");
   
   // The playlist vector makes copies of the shared_ptr pointers.
   std::vector<std::shared_ptr<Song>> playlist;
   playlist.push_back(sp0);
   playlist.push_back(sp1);
   playlist.push_back(sp2);
   playlist.push_back(sp3);
   playlist.push_back(sp1);
   playlist.push_back(sp2);
   for (auto&& sp : playlist) {
      std::wcout << L"Playing " << sp->title_ << 
         L" by " << sp->artist_ << L", use count: " << 
         sp.use_count() << std::endl;
   }
}

int main() {
   CreateSharedPointers();
}

이 예에서는 다음과 같은 출력을 생성합니다.

  

요구 사항

헤더: <memory>

네임스페이스: std

참고 항목

참조

<memory>

shared_ptr 클래스