Why do we even need the “delete[]” operator?

前端 未结 7 887
粉色の甜心
粉色の甜心 2020-12-03 10:02

This is a question that\'s been nagging me for some time. I always thought that C++ should have been designed so that the delete operator (without brackets) wor

7条回答
  •  感动是毒
    2020-12-03 10:32

    I'm a bit confused by Aaron's answer and frankly admit I don't completely understand why and where delete[] is needed.

    I did some experiments with his sample code (after fixing a few typos). Here are my results. Typos:~Base needed a function body Base *b was declared twice

    struct Base { virtual ~Base(){ }>; };
    struct Derived : Base { };
    int main(){
    Base* b = new Derived;
    delete b; // this is good
    
    Base b = new Derived[2];
    delete[] b; // bad! undefined behavior
    }
    

    Compilation and execution

    david@Godel:g++ -o atest atest.cpp 
    david@Godel: ./atest 
    david@Godel: # No error message
    

    Modified program with delete[] removed

    struct Base { virtual ~Base(){}; };
    struct Derived : Base { };
    
    int main(){
        Base* b = new Derived;
        delete b; // this is good
    
        b = new Derived[2];
        delete b; // bad! undefined behavior
    }
    

    Compilation and execution

    david@Godel:g++ -o atest atest.cpp 
    david@Godel: ./atest 
    atest(30746) malloc: *** error for object 0x1099008c8: pointer being freed was n
    ot allocated
    *** set a breakpoint in malloc_error_break to debug
    Abort trap: 6
    

    Of course, I don't know if delete[] b is actually working in the first example; I only know it does not give a compiler error message.

提交回复
热议问题