如何手动删除类的实例?

新手上路,请多包涵

如何手动删除类的实例?

例子:

 #include <iostream>
#include <cstring>

class Cheese {
private:
    string brand;
    float cost;
public:
    Cheese(); // Default constructor
    Cheese(string brand, float cost); // Parametrized constructor
    Cheese(const Cheese & rhs); // Copy construtor
    ~Cheese(); // Destructor
    // etc... other useful stuff follows
}

int main() {
    Cheese cheddar("Cabot Clothbound", 8.99);
    Cheese swiss("Jarlsberg", 4.99);

    whack swiss;
    // fairly certain that "whack" is not a keyword,
    // but I am trying to make a point. Trash this instance!

    Cheese swiss("Gruyère",5.99);
    // re-instantiate swiss

    cout << "\n\n";
    return 0;
}

原文由 kmiklas 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
1 个回答

通用规则本地创建的实例一旦超出范围就会自动删除/处理。动态创建的Instances(Dynamic Memory Allocation)需要手动删除,如下:

删除实例名称;

  • _注意_:不要在~cheese() (~destructor) 中包含delete instance_name 语句,否则会进入循环并崩溃

在上述需要手动删除实例的情况下,建议使用 DMA:

 int main() {
    Cheese cheddar("Cabot Clothbound", 8.99);
    Cheese* swiss = new swiss("Jarlsberg", 4.99);

    delete swiss;

    Cheese swiss("Gruyère",5.99);
    // re-instantiate swiss

    cout << "\n\n";
    return 0;
}

原文由 saurabhsawant0873 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题