I always thought T *p = new T;
was valid C++ for all T
... until I tried
int main()
{
typedef int Array[2];
Array *p = new Array;
}
and got this cute error I couldn't decipher:
error C2440: 'initializing' : cannot convert from 'int *' to 'Array (*)'
Could someone please explain why this is an error?
You can declare an array of any data type (i.e. int, float, double, char) in C. The following ways can be used to declare and initialize an array in C.
Arrays are not assignable. You cannot use an array type variable as LHS operand of assignment operator. An assignment operator shall have a modifiable lvalue as its left operand.
We can create a copy of an array by using the assignment operator (=).
No they don't get freed automatically, but depending on how you allocated each of them, there might be no need to free them actually. You would only need to free them if they point to memory which was returned by malloc and similar allocation functions. Note in this case you don't need to free the array itself.
If you dynamically allocate an array type, you get a pointer to its first element.
§5.3.4 [expr.new] Entities created by a new-expression have dynamic storage duration. If the entity is a non- array object, [...]. If it is an array, the new-expression returns a pointer to the initial element of the array.
So since you're allocating an array type object, you get an int*
out of it:
int *p = new Array;
This is no different to not using the typedef:
int *p = new int[2];
This also doesn't match your T *p = new T;
rule. That is, you definitely can't do this:
int (*p)[2] = new int[2];
I realise this confusion may have been caused by thinking of new ...[]
as a special type of expression different to new ...
, where new Array
fits into the latter case. We often suggest it might be by saying things like "new[]
should always match with delete[]
". Well that rule is a little misleading. What is really meant here is that new
with an array type should always be matched with delete[]
.
The problem here is that array type syntax in C and C++ is a jumbled mess, and typedef
ing an array type to something that doesn't look so jumbled doesn't make it any less so.
The result, in an expression, of dynamically allocating an array is a pointer, not an array. The types are different.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With