开发者

How to delete multiple dynamically allocated arrays in a single delete statement?

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 [开发者_JAVA百科] rdf1,rdf2,rdf3;

What's the right way to do it ?


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;


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?


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜