Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I do "delete p;", but not "delete (p+1);"? Why does delete require an lvalue?

On this page, it's written that

One reason is that the operand of delete need not be an lvalue. Consider:

delete p+1; 
delete f(x); 

Here, the implementation of delete does not have a pointer to which it can assign zero.

Adding a number to a pointer shifts it forward in memory by those many number of sizeof(*p) units.

So, what is the difference between delete p and delete p+1, and why would making the pointer 0 only be a problem with delete p+1?

like image 307
Lazer Avatar asked Dec 10 '22 16:12

Lazer


1 Answers

You can't do p + 1 = 0. For the same reason, if you do delete p + 1 then delete cannot zero out its operand (p+1), which is what the question on Stroustrup's FAQ is about.

The likelihood that you'd ever write delete p+1 in a program is quite low, but that's beside the point...

like image 137
Steve Jessop Avatar answered May 04 '23 15:05

Steve Jessop