What can you "new"

Denis Koroskin 2korden at gmail.com
Sun Mar 22 17:30:22 PDT 2009


On Mon, 23 Mar 2009 03:28:09 +0300, Derek Parnell <derek at psych.ward> 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 wouldn't recommend using that to anyone. That's a *dirty* hack!




More information about the Digitalmars-d mailing list