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

In this page , she wrote that

One reason is because the delete operand does not have to be an lvalue. Consider:

delete p+1; delete f(x); 

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

Adding a number to the pointer shifts it forward in memory by the number of sizeof(*p) elements.

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

+4
source share
4 answers

You cannot do p + 1 = 0 . For the same reason, if you execute delete p + 1 , then delete cannot reset its operand (p + 1), as discussed in the Stroustrup FAQ.

The probability that you have ever written delete p+1 in a program is pretty low, but it's near the dot ...

+8
source

p and p + 1 point to different places, since you correctly said sizeof(*p) units separately. You cannot delete what was not highlighted, but, for example:

 A* p = new A(); p++; delete p-1; 

will remove the original distribution. Removing p + 1 when p + 1 was not originally allocated is undefined; glib is reset with:

 *** glibc detected *** free(): invalid pointer: 0x0804b009 *** 

The implementation cannot be zero p + 1 because p + 1 is not a variable to change. The paragraph said that

 delete p; 

can translate to

 free(p); p = 0; 

That doesn't make sense with p + 1

+5
source

Actually, you can delete rvalue. Nothing in the specification (n3242) precludes this. In practice, does not make any mistakes .

By the way, if the article says

delete operand should not be lvalue

this means that it may or may not be an lvalue. He does not say that the operand cannot be an lvalue.

+1
source

The reason is that none of them are lvalues, so setting them to NULL (or any other value) is simply not possible.

0
source

Source: https://habr.com/ru/post/1307206/


All Articles