【发布时间】:2016-07-11 14:09:13
【问题描述】:
如何手动删除类的实例?
例子:
#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;
}
【问题讨论】:
-
“Cabot Clothbound”切达干酪怎么样 - 来自Cheddar
-
在堆栈上声明的变量(类的实例)可以使用
memset将其内存设置为零(我猜这在某些情况下很有用......),但它的内存不能被释放,直到你声明它的函数范围结束(直到你的 main 结束)。如果你真的想留在堆栈上,你可以用复制构造函数覆盖你的变量内容,但是为什么你不使用堆和指针在这种情况下你可以delete你的实例? -
@EdHeal:这不像香槟。这不是一个受保护的术语。这个名字指的是起源于切达干酪的食谱。有点像百万只“美国”灰松鼠,他们的父母和祖父母甚至从未听说过美国,更不用说把爪子放在那里了!
-
我知道——不幸的是——但切达干酪的英文是最好的。香槟也是英国的另一项发明。又错过了:-(
标签: c++ class instance destructor kill