'new' operator and typedef-ed arrays in C++ [duplicate]
Possible Duplicate:
Is it possible to dynamically create an array of constant size in C++?
This is rather a theoretical question - I wonder why actually operator new[] in C++ returns pointer to first element of array and not actual array (or a pointer to it). This came to me while trying to do something like
typedef int int4[4];
int4* ni4 = new int4;
While I know why this does not work (although it wasn't so clear in the beginning ;)), it really bugs me that code, which in principle is A* ptr= new A;
does not compile. Am I the only one that finds that weird?
What I find strange here is that operator new[]
is used. The code tries to allocate a single instance of an aggregate, which would be legal if the aggregate was a struct
.
But this is the behavior called out by the standard in section [expr.new]
.
However, there's a very simple workaround:
typedef int int4[4];
int4* ni4 = new int4[1];
...
delete [] ni4;
It could probably be argued for the following
new (int[N]); // type int(*)[N]
new int[N]; // type int*
new T; /* T* */
Only in the middle case, N
can be a runtime value. Nevertheless, the spec does not establish such a type difference. Arrays need special handling anyway in almost all cases (as in, you cannot just copy them either). So you should be prepared to handle them specially. For example, you also have to use delete[]
instead of delete
in your case.
Just to make it clear, if the above would be true, then you would need awkward syntax
int (*p)[N] = new (int[N]);
(*p)[N-1] = 0;
p[0][N-1] = 0; /* or, equivalently */
p[N-1] = 0; /* but not this, error! */
You would first need to dereference the array pointer.
It's legacy from C, which actually had it as legacy from B. The entire handling of native arrays in C++ is abysmal but they can't change it. This is the case for many problems in C++.
I'm not quite sure if I understand your question. In C++, as in C, there is no difference between a pointer to the first element of an array and the array itself.
EDIT: As has been pointed out to me, this is not really correct - please forgive my mistake, I've been spending too much time with Java and C# recently ;-)
精彩评论