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:
a actually point to?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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With