简体   繁体   中英

Difference between new int () and new int { } in C++

I know the difference between new int() and new int(10) . In first case 0 is assigned and in second case 10 is assigned to newly created int. But what is the between new int {} . We use {} for array initialization like new a[]{4,5,6} . But for single variable what is the meaning of using braces while initializing?

/* Combined usage and initialized to 0*/
    int *ptr2 = new int();
    cout<<"*ptr2 = "<<*ptr2<<endl;

    /* Allocated memory can be initialized to specific value */
    int*ptr3 = new int(5);
    cout<<"*ptr3 = "<<*ptr3<<endl;

    int* ptr5 = new int{500};
    cout<<"*ptr5 = "<<*ptr5<<endl;

Your output is this:

*ptr2 =  0 

*ptr3 =  5 

*ptr5 =  500 

No difference in your situation.

But in general :

( expression-list )     (1)     
= expression            (2)     
{ initializer-list }    (3) 

1) comma-separated list of arbitrary expressions and braced-init-lists in parentheses

2) the equals sign followed by an expression

3) braced-init-list: possibly empty, comma-separated list of expressions and other braced-init-lists

Reference: http://en.cppreference.com/w/cpp/language/initialization

In the particular case of int (or any integral type eg long ) there is no difference between new int(10) and new int{10} .

Read more about variable initialization .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM