What's the difference between parentheses and no parentheses when new objects are added?

Source: Internet
Author: User

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

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.