2

I begin to use clang to replace gcc. But when I delete[] pointers, it gives warning. But when I change, the warning disappears. Why and how to deal with that?

int *a = new int[1];
int *b = new int[1];
delete[] a, b;
a.cpp:7:17: warning: expression result unused [-Wunused-value]
    delete[] a, b;
int *a = new int[1];
int *b = new int[1];
delete[] a;
delete[] b;

no warning.

1
  • 1
    You can't really blame GCC for missing this. Good C++ style is to put delete in a destructor - one delete per destructor. If you have two things that need to be deleted, you use two members managing one each. And often you don't need to write that delete yourself. E.g. std::vector<int> manages the delete[]for you. Commented Sep 30, 2022 at 7:17

1 Answer 1

5
delete[] a, b;

is parsed as:

(delete[] a), (b);

Which you can really think of as:

delete[] a;
b;

In which case it is pretty clear that you're not doing much with b.

Where's the warning with GCC?

If you use -Wall, gcc will also warn on this since atleast 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
Sign up to request clarification or add additional context in comments.

3 Comments

delete[](a, b) Is this correct?
No. Just do it as two statements.
@zhaozk You can't delete multiple pointers in a single statement. (a, b) is equivalent to b, because of the comma operator.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.