Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Incomplete example from Accelerated c++

44 views
Skip to first unread message

Paul

unread,
Mar 16, 2015, 11:28:32 AM3/16/15
to
Accelerated c++ contains the code below which is discussed for the case n = 0.
If n = 0, I can see that v is an empty vector but I don't see what effect the delete statement has.
The delete statement deletes the iterator one past the end of an empty vector. This seems similar to deleting a null pointer but is not quite the same.
I would think that the delete statement does nothing in the same way that deleting a null pointer does nothing. However, I can't find anything that explicitly says so. Thank you.

Paul

T* p = new T[n];
vector<T> v(p, p + n);
delete[] p;

Luca Risolia

unread,
Mar 16, 2015, 12:23:20 PM3/16/15
to
On 16/03/2015 16:28, Paul wrote:
> Accelerated c++ contains the code below which is discussed for the
> case n = 0. If n = 0, I can see that v is an empty vector but I don't
> see what effect the delete statement has. The delete statement
> deletes the iterator one past the end of an empty vector. This seems
> similar to deleting a null pointer but is not quite the same. I would
> think that the delete statement does nothing in the same way that
> deleting a null pointer does nothing. However, I can't find anything
> that explicitly says so. Thank you.

> T* p = new T[n]; delete[] p;

If I remember well, if n = 0, by standard p cannot be nullptr, but
delete should be safe. You should have a look at the standard for the
exact wording.

Paavo Helde

unread,
Mar 16, 2015, 1:00:20 PM3/16/15
to
Paul <peps...@gmail.com> wrote in
news:210d9637-2b53-4cdb...@googlegroups.com:
p is a pointer to an object allocated by new[], so of course it is safe to
delete[] it. And delete[] works on pointers, not iterators, so whether p
can be interpreted in another context as an iterator or not is besides the
point. Comment out the unneeded second line if this is confusing you.




Bo Persson

unread,
Mar 17, 2015, 7:54:44 AM3/17/15
to
The standard says (in §18.6):

"Required behavior: Return a non-null pointer to suitably aligned
storage (3.7.4), or else throw a bad_alloc exception."

So even if you allocate space for zero elements, you still get a valid
pointer to these zero elements (and possibly for some additional
bookkeeping info).



Bo Persson

0 new messages