kmi*_*las 4 c++ destructor class kill instance
如何手动删除类的实例?
例:
#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;
}
Run Code Online (Sandbox Code Playgroud)
在不知道用例或您想要解决的实际问题的情况下(请阅读XY问题,您的问题就是一个很好的例子)最简单的方法就是重新分配:
Cheese swiss("Jarlsberg", 4.99);
...
swiss = Cheese("Gruyère",5.99);
Run Code Online (Sandbox Code Playgroud)
这当然可能要求你实现一个赋值运算符,但是遵循三个或五个规则你应该这样做(但是如果遵循零规则则不需要赋值运算符).
您可能还使用指针,如果明确要销毁当前swiss
对象:
Cheese* swiss = new Cheese("Jarlsberg", 4.99);
...
delete swiss;
swiss = new Cheese("Gruyère",5.99);
Run Code Online (Sandbox Code Playgroud)
但是指针是一种你应该避免的蠕虫,并且在现代C++中并不需要太多.但是如果你想要多态性,则需要指针(或引用).然后你可以有一个指向实际实例的基类的指针,虚函数之类的东西将按预期工作.
此外,根据您的情况,我们仍然不知道,您当然可以使用范围:
Cheese swiss("Jarlsberg", 4.99);
...
{
Cheese swiss("Gruyère",5.99);
// In here the swiss cheese is a Gruyère
...
}
// Out here the swiss cheese is a Jarlsberg
Run Code Online (Sandbox Code Playgroud)
虽然像这样的阴影变量名称有效,但是你应该避免这是一个坏习惯,因为它会给代码的读者增加混乱.另一方面,即使使用作用域,也没有什么可以阻止您使用任何(有效)变量名称,因此您可以命名外部作用域实例jarlsberg
和内部作用域实例gruyere
,gruyere
然后该对象将在作用域的末尾被销毁像任何其他嵌套范围变量一样将被破坏并"消失".
可以使用作用域来定义类的另一个实例。
Cheese swiss("Toe", 3.14)
{
Cheese swiss("Ear", 15.9);
}
Run Code Online (Sandbox Code Playgroud)
作为一般规则,本地声明的实例在超出范围时会自行销毁。
如果你真的满足销毁奶酪的需求,那么你需要动态分配它。
Cheese *swiss = new Cheese("toe", 3);
// do something with swiss.
delete swiss; // throw it away.
swiss = new Cheese("Ear", 7);
// do something with swiss.
delete swiss; // throw it away.
Run Code Online (Sandbox Code Playgroud)
必须始终手动删除动态分配的内存。