33

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?

Abhinav Gauniyal
  • 7,034
  • 7
  • 50
  • 93
  • 7
    Is there a reason you're using `std::unique_ptr` instead of `std::vector`? – TartanLlama Feb 09 '17 at 15:10
  • 1
    You wouldn't need the `std::memset` to initialize all to `0` because `std::make_unique(bufSize)` will use the expression `new char[bufSize]()`. Notice the default initialization, `()` – WhiZTiM Feb 09 '17 at 15:12
  • @TartanLlama yes. – Abhinav Gauniyal Feb 09 '17 at 15:13
  • 2
    IIRC, if the datum is a class member, a std::vector will allocate some space, and then allocate again on the inevitable resize. (Others have looked at implementations and come to this conclusion.) The buffer pointer can just be null until allocated. As written here it makes no difference, but it matters in other cases. – user1329482 Nov 06 '17 at 20:31
  • 1
    I'm here because I want to allocate and manage a buffer using `unique_ptr` but, at some point, hand it off to a C function as a raw pointer with `buffer.release()`. – Khouri Giordano Mar 16 '19 at 16:35
  • Related: https://stackoverflow.com/questions/58050872/what-does-stdmake-unique-for-overwrite-do-isnt-it-redundant-with-stdmake – ph3rin Aug 17 '21 at 23:14

3 Answers3

42

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.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
13

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'.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
9

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326