Andrei Alexandrescu Wrote: > Derek Parnell wrote: > > On Sun, 22 Mar 2009 14:31:07 -0400, Steve Teale wrote: > > > >> void str() > >> { > >> auto s = new char[]; > >> } > >> > >> void main() > >> { > >> str(); > >> } > >> > >> produces: > >> > >> str.d(3): Error: new can only create structs, dynamic arrays or class > >> objects, not char[]'s. > >> > >> What am I missing here, isn't char[] a dynamic array? > > > > I believe that the message is wrong, or at least misleading. The 'dynamic' > > here does not mean variable-length arrays but not 'static' - as in ... > > address is not known at compile time. > > > > The 'new' is supposed to create something on the heap and return a > > pointer/reference to it. Thus structs, fix-length arrays, and class objects > > are obvious candidates for that. Variable-length arrays are always created > > on the heap anyway, so to ask for a 'new char[]' is asking for the 8-byte > > pseudo-struct for the array to be created on the heap (which would not be > > initialized to anything) and return a pointer to it. This would give you > > one more level of indirection that you're probably not expecting. > > > > The normal way to create an empty (new, as in never been used yet) char[] > > is simply ... > > > > void str() > > { > > char[] s; > > } > > > > But you knew (no pun intended) that already. > > > > > > What you were actually asking for is more like ... > > > > struct dynary > > { > > size_t len; > > void *data; > > } > > > > void str() > > { > > auto s = cast(char[]*)(new dynary); > > } > > > > void main() > > { > > str(); > > } > > > > I think the question is very legit. char[] is a type like any other > type. What if I want to create a pointer to an array?
Well, thanks for that, I already got flamed for asking a beginner question! As you say, the function of new is fuzzy, and the error message is misleading. > > new is a really bad construct. I'm very unhappy that D inherited it. > > > Andrei > > P.S. The way you create a pointer to an array is: > > auto weird = (new char[][1]).ptr;