First look at 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[] A;
int *b=new int[1000];
for (int i=0;i<100;i++) {
cout<<b[i]<<endl;
}
return 0;
}
Not initialized, the result of the output is:
9437380
9443448
3
4
5
6
。。。
Visible, the new operator does not initialize memory.
and 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[] A;
int *b=new int[1000] ();
for (int i=0;i<100;i++) {
cout<<b[i]<<endl;
}
return 0;
}
The output results are:
0
0
0
0
。。
Visible, has been initialized.
=============================================================================
Further thinking:
Define Class A:
Class a{
Public
int A;
A (): A (10) {};
};
Use the statement in the main function:
A *b=new A;
cout<<b->a<<endl;
A *b=new a ();
cout<<b->a<<endl;
The output is 10, and all of the results are initialized.
However, if the constructor of bar A is deleted, the output of the two statements is: random number, 0.
Thus,C + + in the new initialization of the law may be: for classes that have constructors, whether they have parentheses or not, they are initialized with constructors, and if there is no constructor, the default constructor or parameterless constructor is invoked, and new without parentheses allocates only memory space. Memory is not initialized, and new with parentheses is initialized to 0 while allocating memory.
Ps:1. Original address: Http://hi.baidu.com/maxy218/item/8cd098256327c1829d63d1ca
2. Modify Reference: http://bbs.csdn.net/topics/320161716