Is there a way to distinguish between new's and new[]'s return value?
Consider this code:
int *p = new int;
cout << sizeof(*p);
delete p;
As expected the result is 4. Now, consider this other code:
int *p = new int[10];
cout << sizeof(*p);
delete[] p;
I expected to get 40 (the size of the allocated array), however the result is still 4.
Now, suppose I have a function int *foo()
that returns a pointer to a structure created with new
or with new[]
(but I don't know which one):
int *p = foo();
My question is, is there a way (or hack) to know if p
points to a sing开发者_运维问答le integer or an array of integers?
Please keep in mind that this is just a theoretical question. I won't be writing real code in this fashion.
No, there is no way of doing that. But you know the difference, because the code you wrote called new
or new[]
.
The reason by the way that:
cout << sizeof(*p);
gives you 4 in both cases is because p is a pointer to an int, the expression *p means the thing pointed to by such a pointer (i.e. an int) and the size of an int on your platform is 4. This is all evaluated at compile time, so even if new[]
did return a special value, sizeof
would not be able to use it.
No, because your result is an address (that's why you get 4 for sizeof() in both cases). You created it, so you're expected to know what it is.
In both examples the type of p is the same: int *. sizeof operates on the type, not the data. It's computed at compile time.
You have a couple of choices. You can keep track of the array size yourself, or you can venture into using one of the containers in the standard library such as vector< int >. These containers will track the size (e.g. vector< int >::size()) for you.
sizeof(x) returns the amount of memory needed to contain x as declared.
There is no dynamic aspect to this at all.
sizeof (*foo) where foo is a bar *
will always be the same as sizeof(bar)
No, there isn't any way.
Obligatory question: Why do you need to know?
If it's "because I need to know whether to say delete []
or delete
", then just use arrays all the time, if for some obscure reason you can't figure out which one you used in your own code.
Having a function that can return a pointer to a single item or an array is a bad design decision. You can always return a pointer to an array of size 1:
return new int[1];
First, sizeof(*p)
returns always a value to the integer, so it's always returning 4.
Now, how can you know whether p
is pointing to int
or int[]
?
There is no standard way of it. However, you can hack the platform and get it known. For example, if you try printing p[-1], p[-2], ..., p[-4] etc.
for certain compilers (say linux in my case) then you will see a particular pattern in the value of this locations. However, this is just a hack and you cannot rely upon it always.
精彩评论