www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - New with alias

reply tcak <tcak gmail.com> writes:
I write a code as below:

auto result = new char[4];

It allocates memory as expected.



Later I define an alias and do the above step:

alias Pattern = char[4];

auto result = new Pattern;

But compiler says:
Error: new can only create structs, dynamic arrays or class 
objects, not `char[4]`'s



Is this a bug, or `alias` doesn't work how I was thinking?
Mar 09 2020
next sibling parent Bastiaan Veelo <Bastiaan Veelo.net> writes:
On Tuesday, 10 March 2020 at 06:09:23 UTC, tcak wrote:
 I write a code as below:

 auto result = new char[4];

 It allocates memory as expected.
This is a slice of four chars, which can be used as a dynamic array.
 Later I define an alias and do the above step:

 alias Pattern = char[4];
This is an alias for a static array with a fixed length of four chars.
 auto result = new Pattern;

 But compiler says:
 Error: new can only create structs, dynamic arrays or class 
 objects, not `char[4]`'s

 Is this a bug, or `alias` doesn't work how I was thinking?
It is not a bug. You cannot new static arrays. You can do this, though: Pattern pattern; // One static array of four chars. auto patterns = new Pattern[3]; // A slice with three static arrays of four chars. --Bastiaan.
Mar 10 2020
prev sibling parent Steven Schveighoffer <schveiguy gmail.com> writes:
On 3/10/20 2:09 AM, tcak wrote:
 I write a code as below:
 
 auto result = new char[4];
 
 It allocates memory as expected.
 
 
 
 Later I define an alias and do the above step:
 
 alias Pattern = char[4];
 
 auto result = new Pattern;
 
 But compiler says:
 Error: new can only create structs, dynamic arrays or class objects, not 
 `char[4]`'s
 
 
 
 Is this a bug, or `alias` doesn't work how I was thinking?
IMO, even though this is not a bug per se, it's an unnecessary limitation. The reason for the limitation is the syntax of creating a new array is similar to what you would write for allocating a static array on the heap. Therefore, the confusion would be too much to allow it. At one point, there was talk of only allowing the verbose syntax of allocating an array (i.e.): auto arr = new char[](4); And then deprecate the original, eventually replacing it with allocation of a static array on the heap. But the use case of allocating a static array on the heap is pretty obscure, and also it's not impossible to achieve: auto arr = (new char[4][1]).ptr; or struct S { char[4] arr; } auto arr = &((new S).arr); But I can't see why an alias to a static array is not possible to allocate on the heap. The syntax is not confusing. I think it would have to be a special exception in the compiler. It would provide a much more convenient way to allocate such a thing without resorting to the tricks above. -Steve
Mar 10 2020