A little doubt about delete

Can delete be used like this:
delete a,b,c;
Where a,b & c are dynamically allocated variables?

This doesn't give an compiler error, or even a warning. But so doesn't cin >> a,b;!

And I don't know a way to check whether the memory is actually deleted or not...
Wait a minute, what does the comma operator-separator thing do in this context?
Doesn't it by any chance discard b and c?

Edit: as for checking that it works, create some classes with verbose destructors.
1
2
3
4
5
6
7
8
class Thing
{
private:
    int myID;
public:
    Thing(int id): myID(id) {}
    ~Thing() {std::cout << "Thing with ID " << myID << " is dead." << std::endl;}
};

Last edited on
Catfist Wrote:
Wait a minute, what does the comma operator-separator thing do in this context?

I don't know. I was making sure will it be the same as:
1
2
3
delete a;
delete b; 
delete c;


Catfist Wrote:
Doesn't it by any chance discard b and c?

That's exactly what I want to know...
Last edited on
delete a,b,c; only deletes c.
Likewise, cin >> a,b; is the same as cin >> b;

See here: http://msdn.microsoft.com/en-us/library/zs06xbxh%28v=vs.80%29.aspx
Thanks.
BTW, is there a way to make sure if a pointer has been deleted?
Last edited on
AFAIK no, there is no way to know if the address pointed is valid.
However you could use a smart pointer, maybe boost::weak_ptr
Ah well! Thanks for the replies!
delete a,b,c; only deletes c.
Likewise, cin >> a,b; is the same as cin >> b;


Did you test that yourself?
For me, it is the first object which is deleted/read.

Edit:
@ Nisheeth: I don't think so. The language certainly doesn't provide help. From what I know delete p; simply asks for the memory allocated at address p to be marked as not in use. The contents at p are not changed by it, and neither is p itself.
Do correct me if I'm mistaken.
Last edited on
I didn't test these, but...

delete a,b,c; // <- should be same as delete a;

cin >> a,b; // <- should be same as cin >> a;

func( (a,b) ); // <- should be the same as func(b)

It's all about operator precedence. >> and delete (remember that delete is an operator) have a higher precendence than the comma operator (which actually has the lowest precedence of all operators).

Since the func() example isn't about operator precedence, then the comma operator is evaluated before the function call, resulting in the right-most expression (b) being passed to the function.


That said -- the comma operator is stupid. I don't know why it's in the language (other than for parameter lists)
Last edited on
Disch wrote:
the comma operator is stupid. I don't know why it's in the language

Maybe for the same reason goto is? :)
Last edited on
goto at least can have a practical use.

I have yet to see any code ever that makes practical use of the comma operator.
There is a use, namely avoiding having to start a block after an if/while when there's just two small tasks to perform, e.g.
if (foo)a=0,b=0;
Topic archived. No new replies allowed.