Topic: >>new char[0] and new char[1]... differenc
Author: clamage@Eng.Sun.COM (Steve Clamage)
Date: 1995/06/28 Raw View
In article AFUAHyliVA@qsar.chem.msu.su, "Eugene Radchenko" <eugene@qsar.chem.msu.su> writes:
><clamage@Eng.Sun.COM> (Steve Clamage) writes in comp.lang.c++
>>
>>But "char[0]" is not a valid type, and the expression "new char[0]"
>>is not a valid expression. The ARM says so explicitly in 8.2.4, page 136.
>>The C++ draft standard says the same thing.
>
>Certainly char[0] as such is not usable. But what about the common
>technique involving constructs like this:
> class Array {
> int arsize;
> char *p;
> public:
> Array(int size)
> : arsize(size), p(new char[size]) {}
> ~Array() { delete p; }
> int GetSize() { return arsize; }
> void Resize(int newsize); //allocate new block, copy contents, switch
> //pointers, delete old block
> };
>
>Here Array(0) might be necessary (for instance, if Array object is used to
>store dynamically generated objects number of which is not known in advance).
>Generally speaking, what type is `char [size]` ?
In the case of
new char[size]
where 'size' is not a constant-expression and size==0, no space is allocated.
It is similar to the result of
operator new(0)
in that a unique pointer is returned, but you cannot dereference the pointer.
(When I say "no space is allocated" and "you cannot deference the pointer",
I mean that you cannot assume that space was allocated or that it is safe
to dereference the pointer.)
If size is a constant-expression with value 0, the expression is ill-formed.
The type of "char[size]" (where 'size' is not a constant-expression)
isn't an issue, since it can appear only in a new-expression. The
new-expression returns a char* (a pointer to the element type).
If you allow a zero size to be specified for your Array class, you have
to take care never to dereference 'p' when 'arsize' is zero. (You can of
course delete p even when arsize is zero.)
---
Steve Clamage, stephen.clamage@eng.sun.com