make_unique
지정된 인수를 사용하여 작성되는 지정된 형식의 개체를 만들고 unique_ptr을 반환합니다.
// make_unique<T>
template<class T,
class... Types>
unique_ptr<T> make_unique(Types&&... Args)
{
return (unique_ptr<T>(new T(forward<Types>(Args)...)));
}
// make_unique<T[]>
template<class T>
make_unique(size_t Size)
{
return (unique_ptr<T>(new Elem[Size]()));
}
// make_unique<T[N]> disallowed
template<class T,
class... Types>
typename enable_if<extent<T>::value != 0,
void>::type make_unique(Types&&...) = delete;
매개 변수
T
unique_ptr에서 가리키는 개체의 형식입니다.Types
Args에 의해 정의된 생성자 형식입니다.Args
T 유형의 개체에 대한 생성자에 전달할 인수입니다.Elem
T 형식 요소의 배열.Size
새 배열에 공간을 할당할 수 있는 요소의 수입니다.
반환 값
지정된 T 형식의 개체에 대한 unique_ptr입니다.
설명
첫 번째 오버로드는 단일 개체를 사용하고, 두번째 오버로드는 배열에 대해 호출되고, 세번쨰 오버로드는 형식 인수에서 배열의 크기를 지정하는것을 막습니다. (make_unique<T [N]>); 현재 표준에 따라 생성이 지원 되지 않습니다. make_unique를 사용하여 unique_ptr을 배열에 추가하려면 배열 요소를 따로 초기화해야 합니다. 이 오버로드를 고려 하는 경우, std::vector를 사용하는 것이 더 나을 수 있습니다.
make_unique 는 예외 안전성을 위해 신중하게 구현되기 때문에, unique_ptr 생성자를 직접 호출하는 것 대신 make_unique 을 사용하는 것을 추천합니다.
예제
다음 예제에서는 make_unique의 사용 방법을 보여 줍니다. 추가 예제는 방법: unique_ptr 인스턴스 만들기 및 사용를 참조하십시오.
class Animal
{
private:
std::wstring genus;
std::wstring species;
int age;
double weight;
public:
Animal(const wstring&, const wstring&, int, double){/*...*/ }
Animal(){}
};
void MakeAnimals()
{
// Use the Animal default constructor.
unique_ptr<Animal> p1 = make_unique<Animal>();
// Use the constructor that matches these arguments
auto p2 = make_unique<Animal>(L"Felis", L"Catus", 12, 16.5);
// Create a unique_ptr to an array of 5 Animals
unique_ptr<Animal[]> p3 = make_unique<Animal[]>(5);
// Initialize the elements
p3[0] = Animal(L"Rattus", L"norvegicus", 3, 2.1);
p3[1] = Animal(L"Corynorhinus", L"townsendii", 4, 1.08);
// auto p4 = p2; //C2280
vector<unique_ptr<Animal>> vec;
// vec.push_back(p2); //C2280
// vector<unique_ptr<Animal>> vec2 = vec; // C2280
// OK. p2 no longer points to anything
vec.push_back(std::move(p2));
// unique_ptr overloads operator bool
wcout << boolalpha << (p2 == false) << endl; // Prints "true"
// OK but now you have two pointers to the same memory location
Animal* pAnimal = p2.get();
// OK. p2 no longer points to anything
Animal* p5 = p2.release();
}
unique_ptr 에 연결에서 오류 C2280가 표시되는 경우, 거의 삭제 함수인 복사 생성자를 호출 하려고 하는 것 때문입니다.
요구 사항
<메모리>