Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::make_unique<T[]>(size) value-initialization

Tags:

c++

c++11

c++14

Does

std::make_unique<double[]>(1000)

allways value-initialize the elements? Well, I looked into the implementation and clang as well as g++ are using

new T[size]()

doing value-initialization.

But I can't find that a conforming implementation of C++14 / 17 has to do this.

like image 416
wimalopaan Avatar asked Sep 02 '16 10:09

wimalopaan


People also ask

Does make_unique initialize?

You can use make_unique to create a unique_ptr to an array, but you cannot use make_unique to initialize the array elements.

Does make_unique throw?

A little late, but make_unique can itself throw according to cppreference: make_unique "may throw std::bad_alloc or any exception thrown by the constructor of T.

What does std:: make_ unique do?

make_unique prevents the unspecified-evaluation-order leak triggered by expressions like foo(unique_ptr<X>(new X), unique_ptr<Y>(new Y)) . (Following the advice "never say new " is simpler than "never say new , unless you immediately give it to a named unique_ptr ".)

Can unique_ptr be null?

Nullability - a scoped_ptr or unique_ptr can be null, a value object can never be. Polymorphism - a value object is always exactly its static type, but you can substitute in different derived types for a unique_ptr. The previously-held object is automatically destroyed when you do this.


1 Answers

If the standard library is conforming to C++14 then yes it has to do this (use new T[size]). From C++14 §20.8.1.4[unique.ptr.create]/4:

template <class T> unique_ptr<T> make_unique(size_t n);

  • Returns: unique_ptr<T>(new remove_extent_t<T>[n]()).
like image 85
kennytm Avatar answered Oct 05 '22 11:10

kennytm