Original address: Http://hi.baidu.com/maxy218/item/8cd098256327c1829d63d1ca
Put the conclusion first:
C + + initialization in new may be as follows: For classes with constructors, regardless of parentheses, constructors are initialized; if there is no constructor, then new without parentheses allocates only memory space and does not initialize memory. New with parentheses is initialized to 0 while allocating memory.
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 new initialization of the law may be: For a class with constructors, regardless of parentheses, are initialized with constructors; if there is no constructor, the new without parenthesis allocates only the memory space, and does not initialize the memory. New with parentheses is initialized to 0 while allocating memory.