c++ - 在有条件地调用 new 时调用 delete

标签 c++ delete-operator

假设我有以下类(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/

相关文章:

c++ - 64 位环境中的成员变量指针

c++ - 如何将自定义类型保存到 QSettings?

c++ - 如果将 delete[] 应用于非数组指针会发生什么?

c++ - 在 C++ 中销毁动态分配的内存(数组对象)

c++ - 带花括号初始化器列表的已删除构造函数的默认构造

c++ - 找不到以下 Boost 库 : boost_asio

c++ - 如何在运行时以 DAG 的形式组合多个函数

c++ - 替换参数包的包装器类型

c++ - 尝试处理嵌套对象/结构和动态数组时发生内存泄漏或内存错误。可能的 Xcode/malloc 问题

c++ - 删除具有堆成员的对象