①t *p =new T;
②t *p =new T ();
A summary of the differences between the two types of usage.
1. If T is a class type and the user defines a constructor, the effect is identical in both forms, and the defined constructor is called to initialize the internal member variable, but if the member variable is not initialized in this constructor, the member variable is initialized by default-the value is undefined.
2. If T is a class type, but the user does not define any constructors, then we can know that the compiler will synthesize a default constructor for the class, at which point the result of the above two forms is different, and the member variable inside the ① class performs the default initialization at this time, and its value is undefined. However, in ②, when the parentheses are added, the member variables inside the p perform the value initialization, which is initialized in the form of 0 (the integer is 0,bool and the false,string is empty)
3. If T is a built-in type, the value of *p in the form of ① is undefined, and the value in ② is initialized as above.
The following programming tests are performed for each of the above scenarios.
1. The definition constructor is displayed, but the constructor does not initialize the member variables, regardless of a that the ①② output is undefined.
Class Test{public:test () {printf ("constructor\n");} int Geta () Const{return A;} Private:int A;}; int main () {Test *pta = new Test; Test *PTB = new test ();p rintf ("A:%d\n", Pta->geta ());p rintf ("A:%d\n", Ptb->geta ()); return 0;}
2.The definition constructor is displayed, and the constructor defines the row initialization for the member variable, and a in ①② is the constructed value.
Class Test{public:test (): A (0) {printf ("constructor\n");} int Geta () Const{return A;} Private:int A;}; int main () {Test *pta = new Test; Test *PTB = new test ();p rintf ("A:%d\n", Pta->geta ());//output zeroprintf ("A:%d\n", Ptb->geta ());//output Zeroret Urn 0;}
The above two examples show that whenever a constructor is defined, no parentheses are added to the new, and the constructor is called itself.
3. No constructors are defined in the class, and the default constructor for the compiler composition is used.
Class Test{public:int Geta () Const{return A;} Private:int A;}; int main () {Test *pta = new Test; Test *PTB = new test ();p rintf ("A:%d\n", Pta->geta ());//undefined value a->default initializerprintf ("A:%d\n ", Ptb->geta ());//output zeroa->value Initializerreturn 0;}
4. Two forms of the built-in type.
int main () {int *pia = new Int;int *PIB = new int ();p rintf ("%d\n", *pia),//undefined valueprintf ("%d\n", *PIB);//ouput Zero return 0;}