About whether the new C + + is going to initialize the memory problem __c++

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.