How can I make `new[]` default-initialize the array of primitive types?
Asked Answered
D

4

27

Every now and then I need to call new[] for built-in types (usually char). The result is an array with uninitialized values and I have to use memset() or std::fill() to initialize the elements.

How do I make new[] default-initialize the elements?

Dubiety answered 18/3, 2010 at 7:47 Comment(2)
I am not sure whether this is valid, but works fine on VC9. int* p = new int[10]();Pfister
Possible duplicate of How to initialise memory with new operator in C++?Librium
S
36

int* p = new int[10]() should do.

However, as Michael points out, using std::vector would be better.

Sergo answered 18/3, 2010 at 8:3 Comment(2)
You can also the c++11 uniform initialization syntax: new int[10]{}.Rockey
@Fernando: You can now, thanks for pointing this out. You'd have had a hard time finding a compiler that accepted that in May 2010, though. :)Sergo
G
25

Why don't you just use std::vector? It will do that for you, automatically.

std::vector<int> x(100); // 100 ints with value 0
std::vector<int> y(100,5); // 100 ints with value 5

It is also important to note that using vectors is better, since the data will be reliably destructed. If you have a new[] statement, and then an exception is subsequently thrown, the allocated data will be leaked. If you use an std::vector, then the vector's destructor will be invoked, causing the data to be properly deallocated.

Greyhen answered 18/3, 2010 at 7:51 Comment(1)
I totally agree that vector is often better, but still I want new[]. +1 anyway.Dubiety
A
4

This relatively old topic can now be enhanced by another variant. I was using bool, because there is a quite strange specialization for vector<bool>

#include <memory>
...
unique_ptr<bool[]> p{ new bool[count] {false} };

this can now be accessed with the operator[]

p[0] = true;

just like std::vector<T> this is exception safe.

(I suppose this wasn't possible back at 2010 :) )

Audre answered 28/2, 2017 at 21:3 Comment(0)
R
1

Primitive type default initialization example:

int* p = new int[5];          // gv gv gv gv gv (gv - garbage value)
int* p = new int[5]();        // 0  0  0  0  0 
int* p = new int[5]{};        // 0  0  0  0  0  (Modern C++)
int* p = new int[5]{ 1,2,3 }; // 1  2  3  0  0  (Modern C++)
Richela answered 13/4, 2022 at 18:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.