Ramachandra jr Ramachandra jr - 11 months ago 38
C++ Question

Using new to allocate contiguous space vs using a vector?

Why use a new memory location like this when we have vectors?

Are there any Advantages?

bool* arr = new bool(size);

I am not clear what this line does but what I feel is
sets whatever
is given over all
locations starting from address at
and ends at the
given size

std::memset(arr, 0, sizeof(bool) * (num+1));

Answer Source

What this line bool* arr = new bool(size); does?

This line allocates a boolean in the heap and it initializes it to true if size != 0 and to false if size == 0. It then assigns the address of the newly allocated boolean to the boolean pointer arr. So no arrays in to play here.

How I could allocate an array of boolean with new?

The proper way to allocate an array in the heap is to use operator new[]. That is in your case:

bool* arr = new bool[size];

With the advent of smart pointers you could also use std::unique_ptr:

std::unique_ptr<bool[]> arr(new bool[size]);

Thus, you wouldn't have to delete [] afterwards.

Why use a new memory allocation like this when we have vectors?

Well with any other type except bool I would agree but the thing is that there are certain issues with std::vector<bool>.

std::vector<bool> is a specialisation of std::vector<T> that's done mainly for space efficiency (debatable).

However, it behaves similarly but not equally as a regular std::vector<T>. This is attributed mainly to the fact that std::vector<bool> is not a container in the usual STL sense but rather an array of bits. Generaly, use of std::vector<bool> can cause many havocs it's considered a premature optimization and it can even pessimize your performance (see more details here).

Another thing is that in embeded systems that space is crusial, using a raw array instead of a vector is a better option in terms of space efficiency.

What about std::memset(arr, 0, sizeof(bool) * (size));?

std::memset initializes a certain number of bytes in memory (i.e., third input argument) with a given value (i.e., second input argument) starting from address arr (i.e., first input argument). In the example above it will fill arr with 0s up to size number of bytes. That is if arr is an array of size size it will initialize all the elements of this boolean array to false.

However alternatevely, you could use the following scheme:

bool* arr = new bool[size]();


std::unique_ptr<bool[]> arr(new bool[size]());

And thus avoid calls to raw memory manipulators a std::memset that fall in the use with caution category.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download