Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new A[0] -- Legal, but of what use? What does it actually do?

According to the C++03 Standard (5.3.4/7):

When the value of the expression in a direct-new-declarator is zero, the allocation function is called to allocate an array with no elements.

By my reading, this means that this code is legal and has a specified effect:

#include <iostream>
#include <string>
using namespace std;

class A
{
public:
    A() : a_(++aa_) {};
    int a_;
    static int aa_;
};
int A::aa_ = 0;

int main()
{
    A* a = new A[0];
    // cout << "A" << a->a_ << endl; // <-- this would be undefined behavior
}

When I run this code under the debugger, I see that A's constructor is never called. new does not throw, and returns a non-null, apparently valid pointer. However, the value at a->a_ is uninitialized memory.

Questions:

  1. In the above code, what does a actually point to?
  2. What does is mean to "allocate an array with no elements?"
  3. Of what practical use is it to allocate an array with zero elements?
like image 355
John Dibling Avatar asked Dec 20 '25 11:12

John Dibling


1 Answers

In the above code, what does a actually point to?

Points to a zero element array.

What does is mean to "allocate an array with no elements?"

It means that we get a valid array, but of zero size. We can't access the values into it since there are none, but we now that each zero-sized array points to a different location and we can even make an iterator to past-the-end &a[0]. So we can use it just like we use every other array.

Of what practical use is it to allocate an array with zero elements?

It just saves you from checking for n = 0 every time you call new. Note that a static array of zero-size is illegal, since static arrays have static sizes that come from constant expressions. And furthermore, allows you to call any standard or custom algorithm taking a pair of iterators.

like image 121
K-ballo Avatar answered Dec 22 '25 03:12

K-ballo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!