Difference between operator new() and operator new[]()?

后端 未结 5 673
礼貌的吻别
礼貌的吻别 2021-01-04 19:40

Is there any difference between fncs: operator new and operator new[] (NOT new and new[] operators)? Except of course call syntax? I\'m asking because I can allocate X numbe

5条回答
  •  遥遥无期
    2021-01-04 20:12

    In your example code, you're using placement new to perform the construction that operator new[] performs automatically - with the difference that new[] will only perform default construction and you're performing a non-default placement construction.

    The following is more or less equivalent to your example:

    #include 
    
    using namespace std;
    
    struct X
    {
        int data_;
        X(int v=0):data_(v){}
    };
    
    int main(int argc, char* argv[])
    {
        unsigned no = 10;
    
        X* xp = new X[no];
    
        for (unsigned i = 0; i < no; ++i) {
            X tmp(i);
            xp[i] = tmp;
        }
    
        for (unsigned i = 0; i < no; ++i)
        {
            cout << (xp[i]).data_ << '\n';
        }
    
        delete[] xp;
    
        return 0;
    }
    

    The differences in this example are:

    • I believe the example here is more readable (casts can be ugly, and placement new is a pretty advanced technique that isn't often used, so isn't often understood)
    • it properly destroys the allocated objects (it doesn't matter in the example since the object are PODs, but in the general case, you need to call the dtor for each object in the array)
    • it has to default construct the array of objects, then iterate over them to set the actual value for the object - this is the one disadvantage in this example as opposed to yours

    I think that in general, using new[]/delete[] is a much better than allocating raw memory and using placement new to construct the objects. It pushes the complexity of the bookkeeping into those operators instead of having it in your code. However, if the cost of the "default construct/set desired value" pair of operations is found to be too costly, then the complexity of doing it manually might be worthwhile. That should be a pretty rare situation.

    Of course, any discussion of new[]/delete[] needs to mention that using new[]/'delete[]should probably be avoided in favor of usingstd::vector`.

提交回复
热议问题