5

If I have 3 pointers to double :

rdf1 = new double [n];

rdf2 = new double [n];

rdf3 = new double [n];

I want to delete them with a single delete statement. something like :

delete [] rdf1,rdf2,rdf3;

What's the right way to do it ?

2
  • 6
    Would you accept deleting them with no delete statements? std::vector<double> rdf1(n), rdf2(n), rdf3(n); Commented Jul 14, 2011 at 14:36
  • you can write a macro to do this. Commented Oct 3, 2011 at 17:35

3 Answers 3

17

Unfortunately, this is syntactically correct:

delete [] rdf1,rdf2,rdf3;

More unfortunately, it doesn't do what you think it does. It treats , as a comma operator, thus eventually deleting only rdf1 (since operator delete has precedence over operator ,).

You have to write separate delete [] expressions to get the expected behavior.

delete [] rdf1;
delete [] rdf2;
delete [] rdf3;
Sign up to request clarification or add additional context in comments.

Comments

8

To be fair, you can do it as a single statement, just not as a single invocation of the delete [] operator:

(delete [] rdf1, delete [] rdf2, delete [] rdf3);

But why in the world do you care whether it is one statement or three?

2 Comments

+1, just what I wanted to say! delete is not a statement, it's an operator (which is part of the delete-expression). The parentheses are redundant though.
I didn't want to make it complex. Just wondered if it's possible to do the same with a single delete operator. Thanx for your answer
6

No it is not the right way. You have to call delete [] on each of the pointers separately.

The standard form of operator delete[] will take only one parameter.

delete [] rdf1;
delete [] rdf2;
delete [] rdf3;

I always follow one principle that the code I write should be easily understandable by one who works on it after me. So rather than doing this with any fancy constructs I would do it the more commonly known way(which is above).

Comments

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.