假设我有以下类(class):
foo{
~foo();
private:
char *bar;
};
在某些情况下 bar 会创建一个新的 char 数组,那么处理删除它的正确方法是什么?一个简单的 bool 会做还是会被认为是不好的做法?
最佳答案
如果 bar
是 nullptr,那么您可以安全地对其调用 delete:
bar = nullptr;
delete bar;
所以不需要测试,直接删除即可。
3.7.4.2/3:
The value of the first argument supplied to a deallocation function may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call has no effect.
关于c++ - 在有条件地调用 new 时调用 delete,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16934982/