c++ - 新表达式会返回一个指向数组的指针吗?

标签 c++ arrays pointers types new-operator

在此excellent answer by AndreyT ,他解释说,在 C 中,当一个函数需要一个在编译时已知维度的数组时,声明是一个主要的技术级错误

void process_array(int *ptr, size_t plen);

代替

void process_array(int (*arr_ptr)[10]);

此外,他认为许多程序员忘记了第二种选择,只知道第一种。他写道,造成这种行为的原因之一是,当需要动态分配数组并将其传递给第二个版本时,程序员不知道该怎么做;他们已经习惯了返回 int *int *p = malloc(sizeof(*p) * 10)。在 C 中,方法是如他所示

int (*arr_ptr) [10] = malloc(sizeof(*arr_ptr));

这让我开始思考如何在 C++ 中做同样的事情。我知道我们有 std::arraystd::vector 等,但我有兴趣了解 new 的用法。所以我尝试这样做:

typedef int Array10[10];
Array10 *p = new Array10;    // error: cannot convert ‘int*’ to ‘int (*)[10]’

当我将 p 的类型更改为 int* 时,编译器 (GCC 4.8.1) 很高兴。我查阅了 C++11 标准(草案 n3337,§5.3.4/5)以进一步理解这一点,它说:

When the allocated object is an array (that is, the noptr-new-declarator syntax is used or the new-type-id or type-id denotes an array type), the new-expression yields a pointer to the initial element (if any) of the array. [Note: both new int and new int[10] have type int* and the type of new int[i][10] is int (*)[10]end note]

我知道 new int [10] 正在运行;我返回的内容应该使用 delete [] p 而不是 delete p 来释放。然而,我需要的似乎是后者,其中分配的不是整数数组而是数组本身,作为单个/整个对象。

有办法吗?或者我尝试这样做本身就表明了对 C++ 类型系统的误解?或者它是正确的,但标准根本不允许?


旁白:当函数采用大小固定的数组时,如选项 2 中所示,恕我直言,调用函数的最佳做法是声明一个自动数组,而不是求助于动态分配一个并担心清理。

最佳答案

是的,事实上在您引用的标准文本中建议:

int (*arr_ptr)[10] = new int[1][10];

new 表达式返回的指针类型为 int (*)[10],即指向 10 个整数数组的指针。你需要 delete[] 来删除它。

关于c++ - 新表达式会返回一个指向数组的指针吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19467909/

相关文章:

c - C 中的空指针

c++ - 如何将 `std::vector<uchar>` 保存到 `std::ostream` 中?

c++ - 我应该使用以下哪个实现来进行标签分派(dispatch)?为什么?

c - 如果我不说 int i=0 就会出现段错误

javascript - 如何更新 Javascript 对象数组中每个对象的值?

在 c 中打印时类型转换指针差异

c++ - isalpha 总是返回 0

c++ - Visual Studio 中 stricmp 和 _stricmp 的区别?

c - 在C中的数组中迭代

c++ - C++ 中类定义的顺序