Put the conclusion first:
- Brackets call constructors without parameters, and call the default constructor or unique constructor without brackets.
- The initialization rule of C ++ in new may be: for classes with constructors, the constructors are used for initialization regardless of the brackets. If no constructor is available, the new with no parentheses only allocates memory space and does not initialize the memory. The new with parentheses will be initialized to 0 when the memory is allocated.
Run the following code:
# Include <iostream>
Using namespace STD;
Int main ()
{
Int * A = new int [1000];
For (INT I = 0; I <1000; I ++ ){
A [I] = I + 1;
}
Delete [];
Int * B = new int [1000];
For (INT I = 0; I <100; I ++ ){
Cout <B [I] <Endl;
}
Return 0;
}
No initialization. The output result is:
9437380
9443448
3
4
5
6
...
Obviously, the new operator does not initialize the memory.
Slightly change the code (add parentheses () after new ()):
# Include <iostream>
Using namespace STD;
Int main ()
{
Int * A = new int [1000];
For (INT I = 0; I <1000; I ++ ){
A [I] = I + 1;
}
Delete [];
Int * B = new int [1000] ();
For (INT I = 0; I <100; I ++ ){
Cout <B [I] <Endl;
}
Return 0;
}
Output result:
0
0
0
0
..
It can be seen that initialization has been performed.
========================================================== ============================================
Further consideration:
Definition Class:
Class {
Public:
Int;
A (): A (10 ){};
};
Statement used in the main function:
A * B = new;
Cout <B-> A <Endl;
A * B = new ();
Cout <B-> A <Endl;
The output results are both 10 and visible.
However, if the constructor of bar a is deleted, the two statements output random numbers and 0 respectively.
It can be seen that the initialization rule of C ++ in new may be: for classes with constructors, whether there are any parentheses, they are initialized using constructors; if there is no constructor, the new with no parentheses only allocates memory space and does not initialize the memory. The new with parentheses will be initialized to 0 when the memory is allocated.
PS: 1. Original address: http://hi.baidu.com/maxy218/item/8cd098256327c1829d63d1ca
2. Modify reference: http://bbs.csdn.net/topics/320161716