关于删除指针的 Clang 警告

zha*_*ozk 2 c++ clang

我开始使用 clang 来替代 gcc。但是当我删除[]指针时,它会发出警告。但当我改变时,警告就消失了。为什么以及如何处理?

int *a = new int[1];
int *b = new int[1];
delete[] a, b;
Run Code Online (Sandbox Code Playgroud)
a.cpp:7:17: warning: expression result unused [-Wunused-value]
    delete[] a, b;
Run Code Online (Sandbox Code Playgroud)
a.cpp:7:17: warning: expression result unused [-Wunused-value]
    delete[] a, b;
Run Code Online (Sandbox Code Playgroud)

没有警告。

Bil*_*nch 5

delete[] a, b;
Run Code Online (Sandbox Code Playgroud)

被解析为:

(delete[] a), (b);
Run Code Online (Sandbox Code Playgroud)

您可以真正将其视为:

delete[] a;
b;
Run Code Online (Sandbox Code Playgroud)

在这种情况下,很明显您没有对b.

GCC 的警告在哪里?

如果您使用-Wall,gcc 至少自 2007 年起也会对此发出警告(gcc 4.1.2):

<source>: In function 'int main()':
<source>:4:18: warning: right operand of comma operator has no effect [-Wunused-value]
    4 |     delete[] a, b;
      |                  ^
Compiler returned: 0
Run Code Online (Sandbox Code Playgroud)

  • @zhaozk 您不能在单个语句中删除多个指针。由于[逗号运算符](https://en.cppreference.com/w/cpp/language/operator_other#Built-in_comma_o​​perator),`(a, b)` 相当于`b`。 (3认同)