c++ - new A[0] -- 合法,但有什么用?它实际上做了什么?

标签 c++ new-operator

根据 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_ 处的值是未初始化的内存。

问题:

  1. 在上面的代码中,a实际指向什么?
  2. “分配一个没有元素的数组”是什么意思?
  3. 分配零元素数组有什么实际用途?

最佳答案

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/

相关文章:

c++ - 将构造函数参数变成模板参数

c++ - char* 到随机生成的数据

C++ "new"内存分配

c++ - 分配数组而不指定大小

c++ - 检查 C++11 中的类型 #defines

c++ - 错误 : use of undeclared identifier 'std' c++

c++ - 我们可以在 C 或 C++ 中交换两个数字而不传递指针或对交换函数的引用吗?

node.js - 在 node.js 中 require 如何与 new 运算符一起工作?

c++ - 我的代码泄漏了。我该如何解决?

C++ 这段代码有什么问题吗?