Item 16: Use the same form in corresponding uses of new and delete.
如果你用 new 申请了动态内存,请用 delete 来销毁;如果你用 new xx[] 申请了动态内存,请用 delete[] 来销毁:
举个栗子:
1 | std::string* stringPtrl = new std::string; |
上面很容易理解但需要注意typedef:
1 | typedef std::string AddressLines[4]; //每个人的地址有四行, |
由于 AddressLines 是个数组,如果这样使用 new:
1 | std::string *pal = new AddressLines; //注意. "new AddressLines" 返回 |
那就必须匹配 “数组形式“的 delete:
1 | delete pal; //行为未有定义! |
为避免诸如此类的错误,最好尽量不要对数组形式做 typedefs 动作。可以使用更加面向对象的vector、string等对象。