我对 Aaron 的回答有点困惑,坦率地说我不完全理解为什么需要以及在哪里delete[]
需要。
我用他的示例代码做了一些实验(在修正了一些错别字之后)。这是我的结果。错别字:~Base
需要一个函数体
Base *b
被声明了两次
struct Base { virtual ~Base(){ }>; };
struct Derived : Base { };
int main(){
Base* b = new Derived;
delete b; // this is good
<strike>Base</strike> b = new Derived[2];
delete[] b; // bad! undefined behavior
}
编译和执行
david@Godel:g++ -o atest atest.cpp
david@Godel: ./atest
david@Godel: # No error message
delete[]
已删除的修改程序
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
}
编译和执行
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
当然,我不知道delete[] b
第一个例子是否真的有效;我只知道它不会给出编译器错误消息。