如何手动删除类的实例?
例子:
#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 许可协议
通用规则本地创建的实例一旦超出范围就会自动删除/处理。动态创建的Instances(Dynamic Memory Allocation)需要手动删除,如下:
删除实例名称;
在上述需要手动删除实例的情况下,建议使用 DMA: