First of all, I want to assure everyone that I am asking this question with curiosity. I mean, tell me that if I need this then there are problems in my design because I do not want it in the actual code. I hope you have assured me :) For the question now:
For most types of T, we can write
T * p = new T; What will happen if T is an array type?
int (* p) [3] = new ???; // pointer = 3 for array of new ??? I tried to do this:
typedef int arr [3]; Arr * p = new arr; But it does not work.
Is there a valid syntax for this or is it impossible in C ++ if this is impossible, then why? Thanks
Edit : I'm feeling I was not quite clear. I want to be able to use it in this situation: void f (int (& amp;) [3]); Int (* P) [3] = new ???; F (* P);
The reason for this is not that new int [3] Already allocates what you want, an object type int [3] . It is only that the new expression returns , indicates its first element is 5.3.4 / 1: If the unit is a non-array object, then the new- Returns an indicator for the object created by expression. If it is an array, then the new expression returns an indicator to the initial element of the array.
The first element is giving an indicator which allows 3 to be unknown until the runtime, so I think it's already known You have slipped on the flexibility that you are not using. I think reinterpret_cast again type back pointers in ways around it, you want (not necessarily portable), or a int [3] containing one To assign a structure (and use an indicator in its data member) [Edit: Idea of er, yes or Fred overflow, which does not cause any harm, but delete [] instead of delete I need to use.] I think that is ethical, if you write a template that is an unknown type T with new , The template will not work when an array type is T . You'll tell it with the wrong pointer type, and if you fix this (maybe auto ), then you'll delete it incorrectly. Edit question in response to j_kubik:
This is one way to differentiate between array and non-array types if you type a function like this, then that Returns the object that holds the pointer and is able to delete it correctly, then you have a normal new / any type deletion for T.
#include & lt; Iostream & gt; Template & lt; Typename T & gt; Zero MakeMeith_Helper (T *) {std :: cout & lt; & Lt; "Plain version \ n"; } Template & lt; Typename T, int N & gt; Void make_thing_helper (T (*) [N]) {std :: cout & lt; & Lt; "Array Edition \ n"; } Template & lt; Typename T & gt; Zero creature () {make_thing_helper ((* t *) 0); } Int main () {typedef int T1; Type Epiphate T2 [3]; Make_thing & lt; T1 & gt; (); Make_thing & lt; T2 & gt; (); }
Comments
Post a Comment