【问题标题】:Why is 'new int (*)[10]' wrong? [duplicate]为什么'new int (*)[10]' 错了? [复制]
【发布时间】:2022-03-08 05:21:27
【问题描述】:

我试过这段代码:

auto p = new int (*)[10];

但我收到错误消息:

test.cc:8:21: error: expected expression
        auto p = new int (*)[10];
                           ^
1 error generated.

我更改了我的代码:

typedef int array[10];
auto p = new array *;

然后一切顺利。 这是为什么呢?

【问题讨论】:

  • 或许,你试过auto p = new (int (*)[10]); 吗?
  • 如果这真的是您收到的唯一错误消息,那有点糟糕,因为它对您识别问题没有多大帮助。那到底是什么工具链?
  • @WhozCraig GCC 和 Clang 都给出了类似的错误消息。 MSVC 更糟糕,只是说syntax error: ')'。但是错误是完全正确的(但可能不太容易理解),一元*运算符后面应该有一个表达式。
  • 在现代 C++ 中显式使用 new 是一种不好的做法。在这种情况下,您应该使用std::vector<int>std::array<int, 10>

标签: c++ multidimensional-array new-operator


【解决方案1】:

详情请咨询https://en.cppreference.com/w/cpp/language/new

new 不带初始化器的语法是任一

new (type)

new type

在第二种情况下,type 可能不包含括号。上述链接页面也证明了这一点:

new int(*[10])();    // error: parsed as (new int) (*[10]) ()
new (int (*[10])()); // okay: allocates an array of 10 pointers to functions

对于您的情况,这意味着:

auto p = new int (*)[10];     // error: parsed as (new int) ((*)[10])
auto p = new ( int (*)[10] ); // ok

当你使用别名时,你可以写

auto p = new array *;

因为这里type 不包含括号。

【讨论】:

    猜你喜欢
    • 2019-01-11
    • 1970-01-01
    • 2015-05-29
    • 2018-02-25
    • 2018-06-18
    • 1970-01-01
    • 2011-06-10
    • 2017-05-01
    • 1970-01-01
    相关资源
    最近更新 更多