根据 C++03 标准 (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.
根据我的阅读,这意味着这段代码是合法的并且具有指定的效果:
#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
}
当我在调试器下运行这段代码时,我发现 A
的构造函数从未被调用。 new
不会抛出,并返回一个非空的、显然有效的指针。但是,a->a_
处的值是未初始化的内存。
问题:
- 在上面的代码中,
a
实际指向什么? - “分配一个没有元素的数组”是什么意思?
- 分配零元素数组有什么实际用途?
最佳答案
In the above code, what does a actually point to?
指向零元素数组。
What does is mean to "allocate an array with no elements?"
这意味着我们得到了一个有效的数组,但大小为零。我们无法访问其中的值,因为没有值,但我们现在每个零大小的数组都指向不同的位置,我们甚至可以创建一个迭代器来结束 &a[0]
。所以我们可以像使用其他数组一样使用它。
Of what practical use is it to allocate an array with zero elements?
它只是让您免于在每次调用 new
时都检查 n = 0
。请注意,零大小的静态数组是非法的,因为静态数组具有来自常量表达式的静态大小。此外,允许您使用一对迭代器调用任何标准或自定义算法。
关于c++ - new A[0] -- 合法,但有什么用?它实际上做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11074289/