| |
| Posted by Steven Schveighoffer in reply to tcak | PermalinkReply |
|
Steven Schveighoffer
| 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
|