views:

137

answers:

2

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?

+10  A: 

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.

Michael Aaron Safyan
I totally agree that vector is often better, but still I want new[]. +1 anyway.
sharptooth
+5  A: 

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

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

sbi