does make_unique value initializes char array

11,561

Solution 1

All of the make_* functions use value-initialization for the type if you don't provide constructor parameters. Since the array-form of make_unique doesn't take any parameters, it will zero-out the elements.

Solution 2

Yes, all the elements will be value initialized by std::make_unique.

The function is equivalent to:

unique_ptr<T>(new typename std::remove_extent<T>::type[size]())

and

value initialization

This is the initialization performed when a variable is constructed with an empty initializer.

Syntax

new T (); (2)

and

The effects of value initialization are:

3) if T is an array type, each element of the array is value-initialized;
4) otherwise, the object is zero-initialized.

then for each element of type char, they'll be value-initialized (zero-initialized) to '\0'.

Solution 3

According to cppreference, yes:

2) Constructs an array of unknown bound T. This overload only participates in overload resolution if T is an array of unknown bound. The function is equivalent to:

unique_ptr<T>(new typename std::remove_extent<T>::type[size]())
                                       value initialization ^

Value initialization indicated by me.

Share:
11,561
Abhinav Gauniyal
Author by

Abhinav Gauniyal

Passionate software engineer skilled in C++ and System Design. Specializes in performance, concurrency, security and defensive programming. Generalist in many other domains. Here's my Github profile. Currently mastering : c++ python rust css javascript nodejs git react php sql mongodb php networking network-programming Send mail to mail.agauniyal at google's email site if you want to get in touch.

Updated on June 07, 2022

Comments

  • Abhinav Gauniyal
    Abhinav Gauniyal almost 2 years

    For example -

    #include <memory>
    
    int main(){
        const auto bufSize = 1024;
        auto buffer = std::make_unique<char[]>(bufSize);
    }
    

    Is the buffer here already filled with '\0' characters or will I have to manually fill it to avoid garbage values.

    And what would be the possible way to do this, will std::memset(&buffer.get(), 0, bufSize) suffice?