differences between new char[n] and new (char[n])

后端 未结 3 752
攒了一身酷
攒了一身酷 2021-01-03 20:24

Is there any difference between new char[n] and new (char[n])?

I have the second case in a generated code, g++ (4.8.0) gives me

<         


        
3条回答
  •  孤独总比滥情好
    2021-01-03 20:57

      new int [n]
      //Allocates memory for `n` x `sizeof(int)` and returns
      //the pointer which points to the beginning of it. 
    
     +-----+-----+-----+-----+-----+-----+-----+-----+------+------+
     |     |     |     |     |     |     |     |     |      |      |
     |     |     |     |     |     |     |     |     |      |      |
     |     |     |     |     |     |     |     |     |      |      |
     +-----+-----+-----+-----+-----+-----+-----+-----+------+------+
    
    
      new (int [n])
      //Allocate a (int[n]), a square which its item is an array
    +----------------------------------------------------------------+
    |+-----+-----+-----+-----+-----+-----+-----+-----+------+------+ |
    ||     |     |     |     |     |     |     |     |      |      | |
    ||     |     |     |     |     |     |     |     |      |      | |
    ||     |     |     |     |     |     |     |     |      |      | |
    |+-----+-----+-----+-----+-----+-----+-----+-----+------+------+ |
    +----------------------------------------------------------------+
    

    In fact both of them are equal.

     

    Here is the code generated by assembler (just an ignorable difference):

    int n = 10;
    int *i = new (int[n]);
    int *j = new int[n];
    
    i[1] = 123;
    j[1] = 123;
    
    ----------------------------------
    
    !    int *i = new (int[n]);
    main()+22: mov    0x1c(%esp),%eax
    main()+26: sub    $0x1,%eax
    main()+29: add    $0x1,%eax
    main()+32: shl    $0x2,%eax
    main()+35: mov    %eax,(%esp)
    main()+38: call   0x401620 <_Znaj> // void* operator new[](unsigned int);
    main()+43: mov    %eax,0x18(%esp)
    !    int *j = new int[n];
    main()+47: mov    0x1c(%esp),%eax
    main()+51: shl    $0x2,%eax
    main()+54: mov    %eax,(%esp)
    main()+57: call   0x401620 <_Znaj> // void* operator new[](unsigned int);
    main()+62: mov    %eax,0x14(%esp)
    !    
    !    i[1] = 123;
    main()+66: mov    0x18(%esp),%eax
    main()+70: add    $0x4,%eax
    main()+73: movl   $0x7b,(%eax)
    !    j[1] = 123;
    main()+79: mov    0x14(%esp),%eax
    main()+83: add    $0x4,%eax
    main()+86: movl   $0x7b,(%eax)
    

    You must delete both of them by delete [] ...

提交回复
热议问题